5

I have a multidimensional array as follows:

Array(
    [0] => Array
        (
            [name] => item 1
            [quantity] => 2
            [price] => 20.00
        )

    [1] => Array
        (
            [name] => item 2
            [quantity] => 1
            [price] => 15.00
        )

    [2] => Array
        (
            [name] => item 3
            [quantity] => 4
            [price] => 2.00
        )

)

I need the 'grand total' of all these items. Now clearly I could get these by doing the following:

$grand_total = 0;
foreach ($myarray as $item) {
    $grand_total += $item['price'] * $item['quantity'];
}
echo $grand_total;

My question is - can this be done in less lines of code using any of the array functions in PHP?

3 Answers 3

6

no. you would have to define a callback function to use array_reduce. this would even get longer but make the code better reusable.

EDIT: Didn't write PHP for a long time but this should do it:

function sum_total_price_of_items($sum, $item) {
    return $sum + $item['price'] * $item['quantity']
}
echo array_reduce($myarray, "sum_total_price_of_items", 0)
Sign up to request clarification or add additional context in comments.

Comments

2

If you are using PHP >= 5.3 (needed for lambda functions), then the array_reduce solution would be shorter:

$input = array(
    array(
        'name' => 'item 1',
        'quantity' => '2',
        'price' => 20.00,
    ),
    array(
        'name' => 'item 2',
        'quantity' => '1',
        'price' => 15.00,
    ),
    array(
        'name' => 'item 3',
        'quantity' => '4',
        'price' => 2.00,
    ),
);

$total = array_reduce($input, 
                      function($subtotal, $row) {
                          return $subtotal + $row['quantity'] * $row['price']; 
                      });

Comments

1

I love this one:

function GrandTotal($temb, $grand=0) {
    return ($current=array_pop($temb)) ? GrandTotal($temb, $grand + $current['price'] * $current['quantity']) : $grand;
}

echo GrandTotal($myarray);

2 Comments

does php optimize tail recursive functions?
My first guess would be not. Still I love it :).

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.