note 41958 deleted from function.array-walk by aidan
| From: | aidan@php.net | Date: | Sun, 11 Jul 2004 02:07:21 +0000 |
| Subject: | note 41958 deleted from function.array-walk by aidan | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-73024@lists.php.net to get a copy of this message | ||
Note Submitter: shadedecho
----
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
}