note 110933 added to function.array-walk
| From: | espertalhao04 at hotmail dot com | Date: | Wed, 26 Dec 2012 11:35:07 +0000 |
| Subject: | note 110933 added to function.array-walk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-192677@lists.php.net to get a copy of this message | ||
here is a simple and yet easy to use implementation of this function.
the 'original' function has the problem that you can't unset a value.
with my function, YOU CAN!
<?php
function array_walk_protected(&$a,$s,$p=null)
{
if(!function_exists($s)||!is_array($a))
{
return false;
}
foreach($a as $k=>$v)
{
if(call_user_func_array($s,array(&$a[$k],$k,$p))===false)
{
unset($a[$k]);
}
}
}
function get_name(&$e,$i,$p)
{
echo "$i: $e<br>";
return false;
}
$m=array('d'=>'33','Y'=>55);
array_walk_protected($m,'get_name');
var_dump($m); //returns array(0) { }
?>
i called it array_walk_protected because it is protected against the unexpected behavior of
unsetting the value with the original function.
to delete an element, simply return false!!!
nothing else is needed!
unsetting $e, under your created function, will keep the same array as-is, with no changes!
by the way, the function returns false if $a is not array or $s is not a string!
limitations: it only can run user defined functions.
i hope you like it!
----
Server IP: 69.147.83.199
Probable Submitter: 77.54.215.164
----
Manual Page -- http://php.net/manual/en/function.array-walk.php
Edit -- https://master.php.net/note/edit/110933
Del: integrated -- https://master.php.net/note/delete/110933/integrated
Del: useless -- https://master.php.net/note/delete/110933/useless
Del: bad code -- https://master.php.net/note/delete/110933/bad+code
Del: spam -- https://master.php.net/note/delete/110933/spam
Del: non-english -- https://master.php.net/note/delete/110933/non-english
Del: in docs -- https://master.php.net/note/delete/110933/in+docs
Del: other reasons-- https://master.php.net/note/delete/110933
Reject -- https://master.php.net/note/reject/110933
Search -- https://master.php.net/manage/user-notes.php