The array_reduce() function in PHP iterates over an array and reduces it to a single value by applying a user-defined callback function. It’s commonly used to sum numbers, concatenate strings, or process arrays based on custom logic.
array_reduce(array $array, callable $callback, mixed $initial = null)
$numbers = [1, 2, 3, 4, 5];
$sum = array_reduce($numbers, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum;
Output:
15
$words = ['PHP', 'is', 'powerful'];
$sentence = array_reduce($words, function($carry, $item) {
return $carry . ' ' . $item;
}, '');
echo $sentence;
Output:
PHP is powerful
$students = [
['name' => 'Alice', 'score' => 85],
['name' => 'Bob', 'score' => 92],
['name' => 'Charlie', 'score' => 78]
];
$totalScore = array_reduce($students, function($carry, $student) {
return $carry + $student['score'];
}, 0);
echo $totalScore;
Output:
255
$emptyArray = [];
$result = array_reduce($emptyArray, function($carry, $item) {
return $carry + $item;
}, 0);
echo $result;
Output:
0
$numbers = [1, 2, 3, 4, 5];
// First, square the numbers using array_map
$squared = array_map(function($item) {
return $item * $item;
}, $numbers);
// Then, sum the squares using array_reduce
$sumOfSquares = array_reduce($squared, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sumOfSquares;
Output:
55
The array_reduce() function in PHP offers powerful functionality for simplifying array data into a single result. Whether you're summing values, concatenating strings, or applying custom logic to process complex arrays, array_reduce() is highly versatile and flexible. You can enhance its capabilities by combining it with other functions like array_map(), making your code more efficient and readable.