array_walk()
array_walk() — Apply a user supplied function to every member of an array.
Built-in function of PHP 8.5. The manual lists it as available in PHP 4, PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.
What it does
array_walk() is not affected by the internal array pointer of array. array_walk() will walk through the entire array regardless of pointer position.
Signature
array_walk(array|object &$array, callable $callback, mixed $arg = null): true
Parameters
| Parameter | Type | What it takes |
|---|---|---|
| &$array | array|object | The input array. |
| $callback | callable | Typically, callback takes on two parameters. The array parameter's value being the first, and the key/index second. |
| $arg | mixed | If the optional arg parameter is supplied, it will be passed as the third parameter to the callback. |
Return value
Always returns true.
Example
A runnable snippet:
$fruits = array("d" => "lemon", "a" => "orange", "b" => "banana", "c" => "apple"); function test_alter(&$item1, $key, $prefix) { $item1 = "$prefix: $item1"; } function test_print($item2, $key) { echo "$key. $item2\n"; } echo "Before ...:\n"; array_walk($fruits, 'test_print'); array_walk($fruits, 'test_alter', 'fruit'); echo "... and after:\n"; array_walk($fruits, 'test_print');
Output:
Before ...: d. lemon a. orange b. banana c. apple ... and after: d. fruit: lemon a. fruit: orange b. fruit: banana c. fruit: apple
Changelog
| Version | Change |
|---|---|
| 8.2.0 | The return type is true now; previously, it was bool. |
| 8.0.0 | If callback expects the second or third parameter to be passed by reference, this function will now emit an E_WARNING. |
See also
array_walk_recursive(), iterator_apply(), call_user_func_array(), array_map()
All PHP 8.5 built-in functions
Reference card built from the PHP manual page array_walk() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.