Calculate the sum of values in an array

How to Sum Values of an Array With the Same Key in PHP?

Let’s suppose you have an array of items like the following:

$items = [ 'item_1' => ['id' => 1, 'name' => 'Pink Shirt', 'qty' => 2], 'item_2' => ['id' => 2, 'name' => 'Blue Shirt', 'qty' => 3], ];

To sum the values of a specific key (such as qty ) in the array, you can use any of the following:

Using the foreach Loop

You can simply use the foreach loop to sum values of a specific key in an array, for example, in the following way:

// PHP 4+ $sum = 0; foreach ($items as $item) < $sum += $item['qty']; >echo $sum; // 5

Although the code spans a few lines, this would be the fastest way as it’s using the language construct foreach rather than a function call (which is more expensive).

Читайте также:  Использование гиперссылок

Using array_sum() and array_column()

Using the array_column() function, you can get an array of all values from a single column in the input array:

// PHP 5.5+ $itemsQty = array_column($items, 'qty'); echo print_r($itemsQty); // Array ( [0] => 2 [1] => 3 )

You can then pass the resulting array as an argument to the array_sum() function to calculate and return the sum of all values in that array:

// PHP 5.5+ $itemsQty = array_column($items, 'qty'); echo array_sum($itemsQty); // output 5

Using array_sum() and array_map()

Using the array_map() function, you can apply a callback function to each element of the array. You can use this to simply return values of a specific key in the array:

// PHP 4+ function mapArray($item) < return $item['qty']; >$itemsQty = array_map('mapArray', $items); echo print_r($itemsQty); // Array ( [item_1] => 2 [item_2] => 3 )

You can then pass the resulting array as an argument to the array_sum() function to calculate and return the sum of all values in that array:

// PHP 4+ function mapArray($item) < return $item['qty']; >$itemsQty = array_map('mapArray', $items); echo array_sum($itemsQty); // 5

In PHP 5.3+, you may pass in an anonymous callback function directly to the array_map() function:

// PHP 5.3+ echo array_sum(array_map(function($item) < return $item['qty']; >, $items)); // 5

In PHP 7.4+ you may use the shorter syntax with arrow functions:

// PHP 7.4+ echo array_sum(array_map(fn ($item) => $item['qty'], $items)); // 5

Using array_reduce()

You can iteratively sum values of a specific array key and reduce the result to a single value using the array_reduce() function, for example, like so:

// PHP 4+ function sumValues($carry, $item) < $carry += $item['qty']; return $carry; >echo array_reduce($items, 'sumValues'); // 5

In PHP 5.3+, you may pass in an anonymous callback function directly to the array_reduce() function:

// PHP 5.3+ echo array_reduce($items, function($carry, $item) < $carry += $item['qty']; return $carry; >); // 5

Hope you found this post useful. It was published 15 Apr, 2016 (and was last revised 15 Jan, 2022 ). Please show your love and support by sharing this post.

Источник

array_sum

array_sum() returns the sum of values in an array.

Parameters

Return Values

Returns the sum of values as an integer or float; 0 if the array is empty.

Examples

Example #1 array_sum() examples

$a = array( 2 , 4 , 6 , 8 );
echo «sum(a) color: #007700″>. array_sum ( $a ) . «\n» ;

$b = array( «a» => 1.2 , «b» => 2.3 , «c» => 3.4 );
echo «sum(b) color: #007700″>. array_sum ( $b ) . «\n» ;
?>

The above example will output:

User Contributed Notes 6 notes

If you want to calculate the sum in multi-dimensional arrays:

function array_multisum (array $arr ): float $sum = array_sum ( $arr );
foreach( $arr as $child ) $sum += is_array ( $child ) ? array_multisum ( $child ) : 0 ;
>
return $sum ;
>
?>

Example:

echo array_multisum ( $data );

Notably the function converts strings to float and ignores strings if they are not convertable:

$a = array( «String» , 2 , 4 , 6 , 8 );
echo «sum(a) keyword»>. array_sum ( $a ) . «\n» ;

$b = array( «12.3456» , 2 , 4 , 6 , 8 );
echo «sum(b) keyword»>. array_sum ( $b ) . «\n» ;
?>

sum(a) = 20
sum(b) = 32.3456

If you have a case where your array has int in strings, it sums them up as if there were only int in the array!
function sum_mix($a)
return array_sum($a);
>
var_dump(sum_mix([9, 3, ‘7’, ‘3’]));
Response will be int(22)

array_sum() doesn’t «ignore strings if they are not convertible», it converts them to zero. array_product() does the same thing, where the difference between «ignoring» and «converting to zero» is much more obvious.

//you can also sum multidimentional arrays like this;

function arraymultisum (array $arr ) $sum = null ;

foreach( $arr as $child ) $sum += is_array ( $child ) ? arraymultisum ( $child ): $child ;
>
return $sum ;
>

echo arraymultisum (array( 1 , 4 , 5 ,[ 1 , 5 , 8 ,[ 4 , 5 , 7 ]]));

array_sum converts strings to integer and array_sum(2,’2′) returns 4.

  • Array Functions
    • array_​change_​key_​case
    • array_​chunk
    • array_​column
    • array_​combine
    • array_​count_​values
    • array_​diff_​assoc
    • array_​diff_​key
    • array_​diff_​uassoc
    • array_​diff_​ukey
    • array_​diff
    • array_​fill_​keys
    • array_​fill
    • array_​filter
    • array_​flip
    • array_​intersect_​assoc
    • array_​intersect_​key
    • array_​intersect_​uassoc
    • array_​intersect_​ukey
    • array_​intersect
    • array_​is_​list
    • array_​key_​exists
    • array_​key_​first
    • array_​key_​last
    • array_​keys
    • array_​map
    • array_​merge_​recursive
    • array_​merge
    • array_​multisort
    • array_​pad
    • array_​pop
    • array_​product
    • array_​push
    • array_​rand
    • array_​reduce
    • array_​replace_​recursive
    • array_​replace
    • array_​reverse
    • array_​search
    • array_​shift
    • array_​slice
    • array_​splice
    • array_​sum
    • array_​udiff_​assoc
    • array_​udiff_​uassoc
    • array_​udiff
    • array_​uintersect_​assoc
    • array_​uintersect_​uassoc
    • array_​uintersect
    • array_​unique
    • array_​unshift
    • array_​values
    • array_​walk_​recursive
    • array_​walk
    • array
    • arsort
    • asort
    • compact
    • count
    • current
    • end
    • extract
    • in_​array
    • key_​exists
    • key
    • krsort
    • ksort
    • list
    • natcasesort
    • natsort
    • next
    • pos
    • prev
    • range
    • reset
    • rsort
    • shuffle
    • sizeof
    • sort
    • uasort
    • uksort
    • usort
    • each

    Источник

    PHP array_sum() Function

    Return the sum of all the values in the array (5+15+25):

    Definition and Usage

    The array_sum() function returns the sum of all the values in the array.

    Syntax

    Parameter Values

    Technical Details

    Return Value: Returns the sum of all the values in an array
    PHP Version: 4.0.4+
    PHP Changelog: PHP versions prior to 4.2.1 modified the passed array itself and converted strings to numbers (which often converted them to zero, depending on their value)

    More Examples

    Example

    Return the sum of all the values in the array (52.2+13.7+0.9):

    Unlock Full Access 50% off

    COLOR PICKER

    colorpicker

    Join our Bootcamp!

    Report Error

    If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

    Thank You For Helping Us!

    Your message has been sent to W3Schools.

    Top Tutorials
    Top References
    Top Examples
    Get Certified

    W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

    Источник

    How to calculate the sum of values in an array in PHP?

    We can calculate the sum of array elements using the PHP predefined array_sum() function. This function takes the array name as its value and returns the sum of all the elements present within that particular array.

    Example: PHP array_sum() function

    In the given example, we have calculated the sum of all the array elements of the given array named $arr using the PHP predefined array_sum() function.

         

    Sum of all the array elements is: 203

    Apart from using a predefined PHP function, we can also calculate the sum of all the elements of an array using for loop.

    Example: Using for loop

    In the given example, we have calculated the sum of all the array elements of the given array $arr using for loop.

          print("Sum of all the elements is: " . $total); ?>  

    Sum of all the array elements is: 203

    Conclusion

    In this lesson, we have learned how to calculate the sum of all the array elements in PHP. We discussed two methods. At first, we have calculated the sum of all the array elements using the array_sum() function, and second we used the for loop for calculating the sum of all the elements of an array.

    Источник

    PHP Array Sum

    PHP Array Sum

    1. Use the array_sum() Function to Sum the Values of an Array in PHP
    2. Calculate the Sum of All Values of a Multidimensional Array in PHP
    3. Calculate the Sum of a Particular Column of a Multidimensional Array Using sum_array() Function in PHP

    PHP has a built-in function array_sum() , which is used to sum all the values of an array.

    This function takes one parameter, the array you want to sum values. It only takes a one-dimensional and associative array as a parameter.

    The array_sum() returns an integer or float value after adding all the values; if the array is empty, it will return 0 .

    This tutorial demonstrates the uses of array_sum() and how to sum the values of a multidimensional array.

    Use the array_sum() Function to Sum the Values of an Array in PHP

    The array_sum() can only be used for one-dimensional and associative arrays.

    // Sum of the values of a one dimensional array.  $sum_array=array(10,20,30,40,50); echo "Sum of the one-dimensional array is: " echo array_sum($sum_array); echo "
    "
    ;
    // Sum of the values of one associative array. $sum_array=array("val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5); echo "Sum of the associative array is: " echo array_sum($sum_array);

    The above code will sum the values of the corresponding array. In the case of an associative array, the array_sum() will only sum the values, not the keys.

    Sum of the one-dimensional array is: 150 Sum of the associative array is: 152.5 

    Calculate the Sum of All Values of a Multidimensional Array in PHP

    We can use foreach loops for a multidimensional array to calculate the sum of all values.

    php $multi_array = [  ["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50],   ["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5],   ["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100],   ["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5] ];  $sum_array = array(); foreach ($multi_array as $k=>$sub_array)   foreach ($sub_array as $id=>$val)   $sum_array[$id]+=$val;  > > print "Sum of full Array : ".array_sum($sum_array)."
    "
    ;
    ?>

    The code above will first calculate the sum of columns of a multidimensional array and return an array with the sum of columns values. Then we use sum_array() function.

    Calculate the Sum of a Particular Column of a Multidimensional Array Using sum_array() Function in PHP

    As we know, sum_array() cannot return the sum of a multidimensional array, but it can be used with another built-in function, array_column() .

    The array_column() will return an array with keys and values with a column from the given multidimensional array. It takes two mandatory parameters, the array and column or index key.

    php $multi_array = [  ["val1"=>10,"val2"=>20,"val3"=>30,"val4"=>40,"val5"=>50],   ["val1"=>10.5,"val2"=>20.5,"val3"=>30.5,"val4"=>40.5,"val5"=>50.5],   ["val1"=>60,"val2"=>70,"val3"=>80,"val4"=>90,"val5"=>100],   ["val1"=>60.5,"val2"=>70.5,"val3"=>80.5,"val4"=>90.5,"val5"=>100.5] ];  $sum_val1 = array_sum(array_column($multi_array, "val1")); print "Sum of column val1 : ".$sum_val1."
    "
    ;
    $sum_val2 = array_sum(array_column($multi_array, "val2")); print "Sum of column val2 : ".$sum_val2."
    "
    ;
    $sum_val3 = array_sum(array_column($multi_array, "val3")); print "Sum of column val3 : ".$sum_val3."
    "
    ;
    $sum_val4 = array_sum(array_column($multi_array, "val4")); print "Sum of column val4 : ".$sum_val4."
    "
    ;
    $sum_val5 = array_sum(array_column($multi_array, "val5")); print "Sum of column val5 : ".$sum_val5."
    "
    ;
    ?>
    Sum of column val1 : 141 Sum of column val2 : 181 Sum of column val3 : 221 Sum of column val4 : 261 Sum of column val5 : 301 

    We can also use loops with array_sum and array_column() functions to calculate the sum of all values of a multidimensional array.

    Sheeraz is a Doctorate fellow in Computer Science at Northwestern Polytechnical University, Xian, China. He has 7 years of Software Development experience in AI, Web, Database, and Desktop technologies. He writes tutorials in Java, PHP, Python, GoLang, R, etc., to help beginners learn the field of Computer Science.

    Related Article — PHP Array

    Источник

Оцените статью