0

I have an array that looks like this, this array represents number of products in a shopping cart

Array
(
    [0] => Array
        (
            [id] => 1
            [icon] => bus.png
            [name] => Web Development
            [cost] => 500
        )

    [1] => Array
        (
            [id] => 4
            [icon] => icon.png
            [name] => Icon design
            [cost] => 300
        )

    [2] => Array
        (
            [id] => 5
            [icon] => icon.png
            [name] => footer design
            [cost] => 300
        )

)

and i am trying to add the [cost] of each together, since it is a shopping cart I need to display the total. some people might buy single product or 2 or 3 so how do i display the total by adding the cost together I have tried using array_sum($products['cost']) and array_sum($products[0]['cost']) but that does not work

Shairyar
  • 3,268
  • 7
  • 46
  • 86

3 Answers3

1

If you don't want to use any built-in function than you can simply use old technique :)

$sum=0;
foreach ($old as $new) $sum+=$new['cost'];
Muhammad Bilal
  • 2,106
  • 1
  • 15
  • 24
  • http://stackoverflow.com/questions/359732/why-is-it-considered-a-bad-practice-to-omit-curly-braces?lq=1 – Barmar Jan 19 '15 at 11:05
1

Simple use foreach and sum it;

$sum=0;
foreach($product as $key => $value){
    $sum += $value['cost'];
}

Then if you want to sum only the selected products

$sum=0;
foreach($product as $key => $value){
    if(in_array($value['id'], $array_of_selected_product_ids))
        $sum += $value['cost'];
}
dinhokz
  • 895
  • 15
  • 36
0

For PHP >= 5.5, you can take advantage of PHP's array_column() function

$total = array_sum(
    array_column(
        $myArray, 
        'cost'
    )
);

For earlier versions of PHP, you can emulate this using array_map():

$total = array_sum(
    array_map(
        function($value) { 
            return $value['cost']; 
        }, 
        $myArray
    )
);
Mark Baker
  • 209,507
  • 32
  • 346
  • 385