array_reduce() / array_walk()
| Since: | PHP 4(2000) |
|---|
Functions that reduce all array elements into a single value, or apply a callback to each element in sequence.
Syntax
array_reduce(array, callback, initial_value); // Applies a callback to each element of the array. The original array is modified in place array_walk(array, callback, extra_data);
Function List
| Function | Description |
|---|---|
| array_reduce($array, $callback, $initial) | Processes each element from the beginning of the array and reduces them to a single value. The callback receives the accumulated result so far and the current element. |
| array_walk($array, $callback, $arg) | Applies a callback to each element of the array. The first argument of the callback is passed by reference, allowing you to modify the original array directly. |
Sample Code
sample_array_reduce.php
<?php
// Calculate the sum of an array
$prices = [150, 80, 300, 200];
$total = array_reduce($prices, fn($carry, $item) => $carry + $item, 0);
echo $total; // 730
// Find the maximum value
$scores = [85, 92, 78, 95, 88];
$max = array_reduce($scores, fn($carry, $item) => max($carry, $item), 0);
echo $max; // 95
// Concatenate array elements into a string
$words = ['PHP', 'is', 'fun'];
$sentence = array_reduce($words, fn($carry, $item) => $carry . $item, '');
echo $sentence; // PHPisfun
// Convert an associative array to HTML option tags
$options = ['jp' => 'Japan', 'us' => 'United States', 'uk' => 'United Kingdom'];
$html = array_reduce(
array_keys($options),
fn($carry, $key) => $carry . "<option value=\"{$key}\">{$options[$key]}</option>\n",
''
);
echo $html;
// Use array_walk to modify each element of an array
$members = ['item_a', 'item_b', 'item_c'];
array_walk($members, function(&$value, $key) {
$value = ($key + 1) . '. ' . $value; // Prepend a number
});
print_r($members);
// Use array_walk to process an associative array
$scores = ['user1' => 9000, 'user2' => 8000, 'user3' => 3500];
array_walk($scores, function(&$val, $name, $multiplier) {
$val = (int)($val * $multiplier);
}, 50);
print_r($scores);
array_reduce.php
php array_reduce.php
730
95
PHPisfun
<option value="jp">Japan</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
Array
(
[0] => 1. item_a
[1] => 2. item_b
[2] => 3. item_c
)
Array
(
[user1] => 450000
[user2] => 400000
[user3] => 175000
)
Details
array_reduce() combines all elements of an array into a single value. The callback receives the result of the previous call as its first argument and the current element as its second. The third argument sets the initial value used for the first call; if omitted, it defaults to null.
array_walk() applies a callback to each element of the array. If you pass the first argument of the callback by reference (&$value), you can modify the original array directly. You can also pass extra data as the third argument, which is useful when you need a shared parameter — such as a tax rate — across all elements.
For simple totals or element counts, array_sum() / count() is more concise. To transform each element and produce a new array, array_map() is an option.
Omitting the initial value results in null
If you omit the third argument of array_reduce(), the initial value defaults to null. For numeric calculations, explicitly pass 0; for string concatenation, pass ''.
<?php $scores = ['user1' => 9000, 'user2' => 8000, 'user3' => 100]; // Omitting the initial value — $carry is null on the first call $total_wrong = array_reduce(array_values($scores), fn($carry, $item) => $carry + $item); echo $total_wrong; // 17100 (PHP treats null as 0 in arithmetic) // Explicitly passing the initial value (safe) $total_safe = array_reduce(array_values($scores), fn($carry, $item) => $carry + $item, 0); echo $total_safe; // 17100
reduce_initial.php
php reduce_initial.php 17100 17100
For numeric calculations the result may coincidentally match, but when the initial type matters — such as string concatenation or building an array — omitting it is risky.
array_walk ignores the return value of the callback
array_walk() discards the return value of the callback. To modify the array elements, you must pass the first argument by reference using &$value.
NG pattern (returning a value has no effect on the array):
<?php
$items = ['product_a', 'product_b', 'product_c', 'product_d'];
array_walk($items, function($value, $key) {
return strtoupper($value); // return value is ignored
});
print_r($items); // unchanged
walk_ng.php
php walk_ng.php
Array
(
[0] => product_a
[1] => product_b
[2] => product_c
[3] => product_d
)
Modify via reference (correct approach):
<?php
$items = ['product_a', 'product_b', 'product_c', 'product_d'];
array_walk($items, function(&$value, $key) {
$value = strtoupper($value);
});
print_r($items);
walk_ok.php
php walk_ok.php
Array
(
[0] => PRODUCT_A
[1] => PRODUCT_B
[2] => PRODUCT_C
[3] => PRODUCT_D
)
When you want to transform each element and return a new array, array_map() is more appropriate than array_walk().
Passing an empty array returns the initial value as-is
If you pass an empty array, array_reduce() returns the initial value unchanged. This can be used to set a default value.
<?php // array_reduce on an empty array $empty = []; $result = array_reduce($empty, fn($carry, $item) => $carry + $item, 0); echo $result; // 0 (initial value returned as-is) // Using it to provide a default label $names = []; $label = array_reduce($names, fn($carry, $item) => $carry . $item . ', ', '(none)'); echo $label; // (none)
reduce_empty.php
php reduce_empty.php 0 (none)
Practical Patterns
Cart total calculation
Using array_reduce() to aggregate the total price from an array of product objects.
<?php
$cart = [
['name' => 'product_a', 'price' => 300, 'qty' => 3],
['name' => 'product_b', 'price' => 12000, 'qty' => 1],
['name' => 'product_c', 'price' => 5000, 'qty' => 2],
];
$total = array_reduce($cart, function($carry, $item) {
return $carry + $item['price'] * $item['qty'];
}, 0);
echo 'Total: ' . number_format($total) . ' yen';
reduce_cart.php
php reduce_cart.php Total: 22,900 yen
Grouped aggregation
Using array_reduce() to build an associative array that tallies values by name.
<?php
$results = [
['item' => 'product_a', 'sold' => true],
['item' => 'product_b', 'sold' => false],
['item' => 'product_a', 'sold' => true],
['item' => 'product_b', 'sold' => true],
['item' => 'product_a', 'sold' => false],
];
$sales = array_reduce($results, function($carry, $item) {
if ($item['sold']) {
$carry[$item['item']] = ($carry[$item['item']] ?? 0) + 1;
}
return $carry;
}, []);
print_r($sales);
reduce_group.php
php reduce_group.php
Array
(
[product_a] => 2
[product_b] => 1
)
If you find any errors or copyright issues, please contact us.