Open In App

How to Calculate the Sum of Array Elements in PHP ?

Last Updated : 03 Jul, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

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);

?>

Output
103

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;

?>

Output
Sum 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;

?>

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)
{
    // 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;

?>

Output
Sum 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);

?>

Output
15

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
?>

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

?>

Output
The 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

?>

Output
79.21912.5



Next Article

Similar Reads