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

3
  • 5
    For PHP >= 5.5, $total = array_sum(array_column($myArray, 'cost')); Commented Jan 19, 2015 at 10:57
  • 3
    For earlier versions of PHP: $total = array_sum(array_map(function($value) { return $value['cost']; }, $myArray)); Commented Jan 19, 2015 at 10:58
  • thanks @MarkBaker i will go with a solution on second commend, please add this as an answer so i can accept it Commented Jan 19, 2015 at 11:09

3 Answers 3

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'];
Sign up to request clarification or add additional context in comments.

1 Comment

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'];
}

Comments

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
    )
);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.