Multidimensional 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 a β€œtotal” of all these items. Now I could get them 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 smaller lines of code using any of the array functions in PHP?

+4
source share
3 answers

no. you will need to define a callback function to use array_reduce . it will even increase, but will make the code more convenient for reuse.

EDIT: Not written 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) 
+6
source

If you use PHP> = 5.3 (necessary for lambda functions), then the solution to array_reduce will 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']; }); 
+1
source

I like it:

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

Source: https://habr.com/ru/post/1334646/


All Articles