How to use array_reduce() Function In PHP
The array_reduce() function is used to reduce the array elements into a single value that can be of float, integer or string. The function uses a user-defined callback function to reduce the input array.
Syntax
mixed array_reduce
(
array $array,
callable $callback,
mixed $initial = null
);
Example: PHP Program to get the sum of all the Array Elements using the array_reduce() Function.
<?php
$arr = [21, 12, 16, 14, 18, 22];
// Use array_reduce to calculate the sum
$sum = array_reduce(
$arr,
function ($carry, $elm) {
return $carry + $elm;
},
0
);
// Display the result
echo "Sum of Array Values:" . $sum;
?>
Output
Sum of Array Values:103
How to Calculate the Sum of Array Elements in PHP ?
Given an integer array arr of size n, find the sum of all its elements in PHP.
Example: Consider the below examples:
Input : arr[5] = [ 1, 2, 3, 6, 5 ]
Output : 17
Explanation : 1 + 2 + 3 + 6 + 5 = 17
Input : arr[] = [ 15, 12, 13, 10 ]
Output : 50
There are different methods to calculate the sum of array values:
Table of Content
- Using array_sum() Function
- Using for Loop
- Using array_reduce() Function
- Using Recursion
- Using foreach Loop
Contact Us