PHP

Aggregate Array Elements into a Single Value with Reducer

Learn how to use PHP's `array_reduce()` function to iterate over an array and progressively build a single result, such as a sum, concatenation, or complex data structure.

<?php
$numbers = [10, 20, 30, 40, 50];

// Example 1: Calculate the sum of all numbers
$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0); // Initial carry value is 0

echo "Sum of numbers: " . $sum . "
"; // Output: 150

$words = ['Hello', 'World', 'PHP', 'Arrays'];

// Example 2: Concatenate words into a sentence
$sentence = array_reduce($words, function($carry, $item) {
    return $carry . ' ' . $item;
}); // No initial carry, first element becomes carry

echo "Sentence: " . trim($sentence) . "
"; // Output: Hello World PHP Arrays

$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'user'],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin']
];

// Example 3: Count users by role
$rolesCount = array_reduce($users, function($carry, $user) {
    $role = $user['role'];
    $carry[$role] = ($carry[$role] ?? 0) + 1;
    return $carry;
}, []); // Initial carry is an empty array

echo "
Roles Count:
";
print_r($rolesCount);

/*
Expected Output:
Sum of numbers: 150
Sentence: Hello World PHP Arrays

Roles Count:
Array
(
    [admin] => 2
    [user] => 1
)
*/
?>
How it works: The `array_reduce()` function iterates through an array, passing the value of each element to a callback function. The callback's return value is then passed as the `carry` argument to the next iteration. This allows you to 'reduce' an array to a single value, whether it's a sum, a string, or a more complex data structure like a tally of categories.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs