What are the advantages and disadvantages of using array_reduce versus array_sum for summing values in PHP arrays?
When summing values in PHP arrays, both `array_reduce` and `array_sum` can be used. Advantages of using `array_sum`: - `array_sum` is a built-in function specifically designed for summing values in an array, making it more straightforward and easier to use. - It is more concise and readable compared to `array_reduce`. Disadvantages of using `array_sum`: - `array_sum` can only be used for summing values and does not provide the flexibility to perform custom operations during the reduction process. Advantages of using `array_reduce`: - `array_reduce` allows for custom operations to be performed during the reduction process, providing more flexibility. - It can be used for more complex reduction operations other than just summing values. Disadvantages of using `array_reduce`: - `array_reduce` requires a callback function to define the reduction operation, making it slightly more complex and less straightforward than `array_sum`.
// Using array_sum
$array = [1, 2, 3, 4, 5];
$sum = array_sum($array);
echo $sum; // Output: 15
// Using array_reduce
$array = [1, 2, 3, 4, 5];
$sum = array_reduce($array, function($carry, $item) {
return $carry + $item;
}, 0);
echo $sum; // Output: 15