note 22072 deleted from function.array-walk by torben
| From: | torben@php.net | Date: | Wed, 05 Jun 2002 17:05:37 +0000 |
| Subject: | note 22072 deleted from function.array-walk by torben | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-31499@lists.php.net to get a copy of this message | ||
I have written a function that allows you to walk an array while passing as many arguments into the
function as needed:
function my_array_walk() {
if (func_num_args() < 3)
die ("You must supply at least 3 arguments");
$my_array = func_get_arg(0);
$my_func = func_get_arg(1);
for ($x = 2; $x < func_num_args(); $x++)
$my_data[$x - 2] = func_get_arg($x);
$my_keys = array_keys($my_array);
for ($x = 0; $x < sizeof ($my_keys); $x++) {
$eval_string = "$my_func(\$my_array[$my_keys[$x]],".
" \$my_keys[$x]";
for ($y = 0; $y < sizeof ($my_data); $y++)
$eval_string .= ", \"\$my_data[$y]\"";
$eval_string .= ")";
eval("$eval_string;");
}
}
So, for example, I could have an array:
$this = array(
"a" => "first element",
"b" => "second element",
"c" => "third element"
);
Create a function for the array elements:
function my_array_function($item, $key, $first, $second, $third) {
echo "$key: $item, $first, $second, $third\n";
}
And then tie it to my array with my_array_walk:
$first = "first argument";
$second = "second argument";
my_array_walk($this, 'my_array_function', $first, $second,
"third");
The output is:
a: first element, first argument, second argument, third
b: second element, first argument, second argument, third
c: third element, first argument, second argument, third
You can use it with any number of arguments after the 'function' in my_array_walk, so long
as your corresoonding function ahs the correct number of arguments:
function my_array_function($item, $key, $first, $second, $third,
$fourth, $fifth) {
echo "$key: $item, $first, $second, $third, $fourth,",
" $fifth\n";
}
my_array_walk($this, 'my_array_function', $first, $second,
"third", 4, 5);
Will output:
a: first element, first argument, second argument, third, 4, 5
b: second element, first argument, second argument, third, 4, 5
c: third element, first argument, second argument, third, 4, 5
This could be extremely useful for those of you who can't stand the one argument limitation to
array_walk's called function.