How can the array_reduce() function be utilized to sum values in PHP without using a foreach loop?
To sum values in PHP without using a foreach loop, you can utilize the array_reduce() function. This function iterates over an array and applies a callback function to each element, accumulating a final result. By providing a callback function that adds each element to the accumulator, you can easily sum up the values in the array without the need for a foreach loop.
$array = [1, 2, 3, 4, 5];
$sum = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum; // Output: 15
Related questions
-
associative array arrow operator key-value pairs
-
PHP data iteration grouping
-
PHP URL redirection header function