How to Calculate the sum of values in an Array in PHP

You can use the PHP array_sum() function calculate the sum of values in an array. The array_sum() function returns the sum of all the numeric values in an array.

Read Also: How to Remove Last Element From An Array In PHP

PHP array_sum() Function Syntax

array_sum(array)

First let’s see the $stack array output :

<?php
$stack = array("10", "12", "21", "72", "12");
print_r($stack);
?>

Output:

Array
(
    [0] => 10
    [1] => 12
    [2] => 21
    [3] => 72
    [4] => 12
)

$stack array have 5 elements and we want to sum of all element values.

Calculate the sum of values in an array

Now we will use PHP array_sum() function to calculate the sum of values in an array like in below example.

<?php
$stack = array("10", "12", "21", "72", "12");

// calculate the sum of values in an array
$sum = array_sum($stack);
echo ($sum);
?>

Output:

127

Leave A Reply

Your email address will not be published.