Using array_walk() with a User-Defined Callback Function to Process Each Array Element
array_walk() applies a user‑defined callback to each element of an array without affecting the internal pointer, accepting the array, a callable function, and optional userdata, returning TRUE on success; the article explains its parameters, behavior, and provides PHP code examples demonstrating typical usage.
Function Overview
The array_walk() function applies a user‑defined callback to each element of an array. It does not depend on the array's internal pointer and traverses the entire array regardless of pointer position.
Parameters
array – the input array.
funcname – a callable that typically receives the element value as the first argument and the key as the second. The callback may also accept an optional third argument userdata .
userdata – optional data passed to the callback as the third parameter.
Return Value
Returns TRUE on success, or FALSE on failure.
Example
"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: appleLaravel Tech Community
Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.