1

How does one add all the integer values in an array? For example, if I have this array:

array(2) {
    ["cart_2"]=> int(5)
    ["cart_1"]=> int(3)
}

What should I use to display the sum of its values (8)?

0

1 Answer 1

1

Using the PHP function array_sum() would do just that. The very definition of the function is "Calculate the sum of values in an array", which is exactly what you're looking for.

$arr = array("cart_2" => 5, "cart_1" => 3);

echo array_sum($arr);  // prints 8

This function can also deal with floats, such as 3.14 and 2.71 - so it doesn't have to be integers, as long as they are numbers. It will ignore any strings that does not start with numbers (so the value 2text would add 2, but the string text 2 would not), but you should note that each boolean true will add the value 1 to the sum.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.