What are array_reduce and array_walk in PHP?
Published in
3 min readJan 4, 2023
I liked to use array_reduce and array_walk in PHP. These are my notes about array_reduce and array_walk.
What is array_reduce?
If you are coming from the JS side, mostly you know the reduce() function. I think it is popular on the JS side.
When I look at PHP documents there is a short description of it;
Iteratively reduce the array to a single value using a callback function
Syntax:
array_reduce(array, callback, initial)
Parameters:
- array: It is the input array that will be reduced to a single value.
- callback: It is a callback function that determines how the array should be reduced.
- initial: It is an optional value that will be used at the beginning of the process, or as a final result in case the array is empty.
Example:
$a = [1, 2, 3, 4, 5, 6];
$num1 = array_reduce($a, function ($num1, $num2) {
return $num1 + $num2;
}, 0);
echo $num1;
// This will print out 21
// Alternative with foreach
$a = [1, 2, 3, 4, 5, 6];
$result = 0;
foreach ($a as $value) {
$result += $value;
}
var_dump($value); // this will print out 6
echo $result;
// This will print out 21