How to Calculate the Sum of Array Elements in PHP ?
Last Updated :
03 Jul, 2024
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:
Using array_sum() Function
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
// Array with values
$arr = [21, 12, 16, 14, 18, 22];
// Calculating sum of array elements
$sumofelements = array_sum($arr);
print_r($sumofelements);
?>
Using for Loop
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];
// Initialize sum with 0
$sum = 0;
// Loop through the array and add
// each element to the sum
for ($i = 0; $i < sizeof($arr); $i++) {
$sum = $sum + $arr[$i];
}
// Display the result
echo "Sum of Array Values:" . $sum;
?>
OutputSum of Array Values:103
Using array_reduce() Function
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];
// 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;
?>
OutputSum 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)
{
// Base or terminating condition
if ($n <= 0) {
return 0;
}
// Calling method recursively
return sumofElements($arr, $n - 1) + $arr[$n - 1];
}
$arr = [21, 12, 16, 14, 18, 22];
$sum = sumofElements($arr, sizeof($arr));
// Display the result
echo "Sum of Array Values:" . $sum;
?>
OutputSum of Array Values:103
Using foreach Loop
To calculate the sum of array elements in PHP using a `foreach` loop, initialize a sum variable to 0, then iterate through each element of the array, adding its value to the sum. Finally, echo or return the sum.
Example: PHP script sums elements of an array `[1, 2, 3, 4, 5]`, outputs result (`15`) to console using `fwrite(STDOUT, $sum . PHP_EOL);`.
PHP
<?php
$array = [1, 2, 3, 4, 5];
$sum = 0;
foreach ($array as $value) {
$sum += $value;
}
// Output the sum to console
fwrite(STDOUT, $sum . PHP_EOL);
?>
Using array_walk()
In PHP, array_walk() iterates through an array, applying a callback function to each element. To calculate the sum of array elements using array_walk(), accumulate values in a variable passed by reference within the callback function.
Example: In this example we are following above explained approach.
PHP
<?php
$array = [1, 2, 3, 4, 5];
$sum = 0;
array_walk($array, function($value) use (&$sum) {
$sum += $value;
});
echo $sum; // Output: 15
?>
Using array_map()
This method utilizes array_map() to apply a simple identity function to each element and then array_reduce() to sum the elements.
Example: In this example, the sumArrayElements function first defines an identity function that returns its input unchanged. It then applies this identity function to each element of the input array using array_map(), effectively keeping the array the same.
PHP
<?php
function sumArrayElements($array) {
// Identity function to pass each element unchanged
$identity = function($element) {
return $element;
};
// Use array_map to apply the identity function to each element
$mappedArray = array_map($identity, $array);
// Use array_reduce to sum the elements of the mapped array
$sum = array_reduce($mappedArray, function($carry, $item) {
return $carry + $item;
}, 0);
return $sum;
}
$arr1 = [1, 2, 3, 6, 5];
echo "The sum of the array elements is: " . sumArrayElements($arr1) . "\n";
// Output: The sum of the array elements is: 17
$arr2 = [15, 12, 13, 10];
echo "The sum of the array elements is: " . sumArrayElements($arr2) . "\n";
// Output: The sum of the array elements is: 50
?>
OutputThe sum of the array elements is: 17
The sum of the array elements is: 50
Using array_product() Function
The array_product() function multiplies all the values in an array and returns the product. However, by dividing the result of this function by each element, you can calculate the sum of the array. This approach is less common and not as efficient as others but demonstrates a creative use of PHP functions.
Example:
PHP
<?php
// Function to get the sum of array elements using array_product
function sum_array_elements($arr) {
$product = array_product($arr);
$sum = 0;
foreach ($arr as $value) {
$sum += $product / $value;
}
return $sum / count($arr);
}
// Example usage:
$arr = [1, 2, 3, 6, 5];
echo sum_array_elements($arr); // Output: 17
$arr = [15, 12, 13, 10];
echo sum_array_elements($arr); // Output: 50
?>
Similar Reads
How to calculate total time of an array in PHP ?
Given an array containing the time in hr:min:sec format. The task is to calculate the total time. If the total time is greater then 24 hours then the total time will not start with 0. It will display the total time. There are two ways to calculate the total time from the array. Using strtotime() fun
2 min read
How to count all array elements in PHP ?
We have given an array containing some array elements and the task is to count all elements of an array arr using PHP. In order to do this task, we have the following methods in PHP:Table of ContentUsing count() MethodUsing sizeof() MethodUsing a loopUsing iterator_count with ArrayIteratorUsing arra
4 min read
How to get the First Element of an Array in PHP?
Accessing the first element of an array in PHP is a common task, whether they are indexed, associative, or multidimensional. PHP provides various methods to achieve this, including direct indexing, and built-in functions.Below are the approaches to get the first element of an array in PHP:Table of C
4 min read
How to Create an Array of Given Size in PHP?
This article will show you how to create an array of given size in PHP. PHP arrays are versatile data structures that can hold multiple values. Sometimes, it's necessary to create an array of a specific size, either filled with default values or left empty. Table of Content Using array_fill() Functi
3 min read
How to Add Elements to the End of an Array in PHP?
In PHP, arrays are versatile data structures that can hold multiple values. Often, you may need to add elements to the end of an array, whether it's for building a list, appending data, or other purposes. PHP provides several ways to achieve this. In this article, we will explore different approache
3 min read
PHP Program to Find Duplicate Elements from an Array
Given an array containing some repeated elements, the task is to find the duplicate elements from the given array. If array elements are not repeated, then it returns an empty array.Examples:Input: arr = [1, 2, 3, 6, 3, 6, 1]Output: [1, 3, 6]Input: arr = [3, 5, 2, 5, 3, 9]Output: [3, 5]There are two
6 min read
How to Find the Largest Element in an Array in PHP?
Given an array containing some elements, the task is to find the largest element from an array in PHP. PHP provides several ways to achieve this, each with its own advantages and use cases. Below are the approaches to find the largest element in an array in PHP:Table of ContentUsing max() FunctionUs
4 min read
How to Remove Last Element from an Array in PHP ?
Removing the last element from an array is a common operation in PHP. There are several approaches to achieve this. In this article, we will explore different methods to remove the last element from an array.Table of ContentUsing array_pop() FunctionUsing array_slice() FunctionUsing unset() Function
3 min read
How to Replace an Element Inside Array in PHP ?
Given an array containing some elements, the task is to replace an element inside the array in PHP. There are various methods to manipulate arrays, including replacing elements. Examples:Input: arr = [10, 20, 30, 40, 50], index_1 = 100Output: [10, 100, 30, 40, 50]Input: arr = ['GFG', 'Geeks', 'Hello
3 min read
Create an Array of Cumulative Sum in PHP
The cumulative sum array is an array where each element is the sum of all previous elements in the original array up to the current index. This article explores different methods to create an array of cumulative sums in PHP. What is a Cumulative Sum Array?A cumulative sum array is an array where eac
3 min read