array_reduce(): Simplifying an array into a single result using custom logic

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.

Syntax

array_reduce(array $array, callable $callback, mixed $initial = null)
  • $array: The array to iterate through.
  • $callback: The function applied to each element. It takes two parameters: the accumulator (carry) and the current item.
  • $initial (optional): The starting value for the accumulator.

Example 1: Summing Simple Array Values

$numbers = [1, 2, 3, 4, 5];

$sum = array_reduce($numbers, function($carry, $item) {
    return $carry + $item;
}, 0);

echo $sum;
Output:
15

Example 2: Concatenating Strings

$words = ['PHP', 'is', 'powerful'];

$sentence = array_reduce($words, function($carry, $item) {
    return $carry . ' ' . $item;
}, '');

echo $sentence;
Output:
 PHP is powerful

Example 3: Using Associative Arrays

$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

Example 4: Handling an Empty Array

$emptyArray = [];

$result = array_reduce($emptyArray, function($carry, $item) {
    return $carry + $item;
}, 0);

echo $result;
Output:
0

Example 5: Combining with array_map()

$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

Conclusion

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.


Joining Two Arrays by array_merge
Array REFERENCE
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer