Jwk895 Jwk895 - 4 months ago 9
PHP Question

Add up multiple value in array

I am looking for a quick solution to add up multiple values I have assigned in a array.

$cars = array(
"name" => "cars",
"checkout" => 5,20,40,
"car_cost" => 240.00
);


I want to add up the "checkout" of the array so I can get the value of 65 to echo out on my site.

Thanks

Answer

Your array syntax is not creating what you think it is. What you are doing is setting the key "checkout" to 5. Then you are setting the key 0 to 20 and 1 to 40.

What you really want is:

$cars = array(
    "name" => "cars",
    "checkout" => array(5,20,40),
    "car_cost" => 240.00
);

You want to save your values as an array. Then you can do:

$totalCars = array_sum($cars["checkout"]);