Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multi-Dimensional Array, Multiplication and Addition in PHP

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?

like image 603
calumbrodie Avatar asked Feb 25 '23 10:02

calumbrodie


2 Answers

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)
like image 109
mschneider Avatar answered Mar 19 '23 10:03

mschneider


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']; 
                      });
like image 39
Jon Avatar answered Mar 19 '23 12:03

Jon