How to Calculate the Sum of Array Elements in PHP ?
Last Updated :
28 Nov, 2023
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:
The array_sum() function returns the sum of all the values in an array (one-dimensional and associative). It takes an array parameter and returns the sum of all the values in it.
Syntax
int|float array_sum( array $array );
Example: PHP Program to get the sum of all the Array Elements using the array_sum() Function.
PHP
<?php
$arr = [21, 12, 16, 14, 18, 22];
$sumofelements = array_sum ( $arr );
print_r( $sumofelements );
?>
|
We can use for loop to calculate the sum of array elements. First, we declare a variable and initialize with zero and then loop over array elements and sum up each array element in the declared variable.
Syntax
$sum = 0;
for ( $i = 0; $i < sizeof($arr); $i++ ) {
$sum = $sum + $arr[i];
}
Example: PHP Program to get the sum of all the Array Elements using For Loop.
PHP
<?php
$arr = [21, 12, 16, 14, 18, 22];
$sum = 0;
for ( $i = 0; $i < sizeof( $arr ); $i ++) {
$sum = $sum + $arr [ $i ];
}
echo "Sum of Array Values:" . $sum ;
?>
|
Output
Sum of Array Values:103
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
<?php
$arr = [21, 12, 16, 14, 18, 22];
$sum = array_reduce (
$arr ,
function ( $carry , $elm ) {
return $carry + $elm ;
},
0
);
echo "Sum of Array Values:" . $sum ;
?>
|
Output
Sum of Array Values:103
Using Recursion
We can use recursion to calculate the sum of array values. The recursive calculates the sum of an array by breaking it down into two cases: the base case, where if the array is empty the sum is 0; and the recursive case, where the sum is calculated by adding the first element to the sum of the remaining elements which is computed through a recursive call with the array shifted by one position and size reduced by one.
Example: PHP Program to get the sum of all the Array Elements using Recursion.
PHP
<?php
function sumofElements( $arr , $n )
{
if ( $n <= 0) {
return 0;
}
return sumofElements( $arr , $n - 1) + $arr [ $n - 1];
}
$arr = [21, 12, 16, 14, 18, 22];
$sum = sumofElements( $arr , sizeof( $arr ));
echo "Sum of Array Values:" . $sum ;
?>
|
Output
Sum of Array Values:103
Share your thoughts in the comments
Please Login to comment...