note 41958 added to function.array-walk
| From: | shadedecho at rn2 dot php dot net | Date: | Tue, 27 Apr 2004 18:15:46 +0000 |
| Subject: | note 41958 added to function.array-walk | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-68897@lists.php.net to get a copy of this message | ||
burrowballer69 at hotmail dot com:
Ok, I see two problems with your example:
1. you call "echo array_walk()", which is faulty by design (at least from what I think
your code is trying to do, because array_walk() returns a bool which indicates success or failure of
the "walk", not what is "return"d from the callback function.
Instead, how about:
function function_name($value, $key)
{
echo $value;
}
foreach($array as $key => $value)
{
my_array_walk($value, 'function_name');
}
2. by doing the foreach() on a single dimensional array, the $value variable in each iteration of
the loop (in your example at least) is just a string ("goats" or "milk"), and so
passing a string value into array_walk() when its expecting an array, would expectedly give
unexpected results.
*********************************
However, was your intention to have each string treated as an array of characters?
PHP gives the {} operators, which allow you to reference the single character at a position in the
string's "array" of characters.
i don't think that array_walk() by default would use the {}, it probably assumes a traditional
array and uses [] appropriately. You could write your own version of array_walk for a string using
the {} operators though, and i bet it would work the same.
maybe, use a wrapper, which for your example might look something like this:
function string_walk($mystring,$callback,$userdata = null) {
for ($i=0; $i<strlen($mystring); $i++) {
call_user_func_array($callback,array($mystring{$i},$i,$userdata));
}
}
function my_array_walk($myarray,$callback,$userdata = null) {
if (is_string($myarray)) string_walk($myarray,$callback,$userdata);
else array_walk($myarray,$callback,$userdata);
}
$thearray = array('goat','milk');
function function_name($value, $key)
{
echo $value; // notice this is changed to resolve #1
}
foreach($thearray as $key => $value)
{
my_array_walk($value, 'function_name');
// again, above line changed to resolve #1
}
----
Manual Page -- http://www.php.net/manual/en/function.array-walk.php
Edit -- http://master.php.net/manage/user-notes.php?action=edit+41958
Delete -- http://master.php.net/manage/user-notes.php?action=delete+41958&report=yes
Reject -- http://master.php.net/manage/user-notes.php?action=reject+41958&report=yes
Search -- http://master.php.net/manage/user-notes.php