Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get min/max value from array based on condition

Tags:

arrays

php

$array = [ [ 'Name' => 'Product 1', 'Quantity' => 0, 'Price' => 70  ], 
           [ 'Name' => 'Product 2', 'Quantity' => 2, 'Price' => 100 ],
           [ 'Name' => 'Product 3', 'Quantity' => 2, 'Price' => 120 ] ];

echo min( array_column( $array, 'Price' ) ); // 70

It does get me the min price, but I also want to check for quantity, in that case 100 would be the lowest.

Is there an elegant way to do this without looping?

like image 760
eozzy Avatar asked Dec 03 '25 16:12

eozzy


1 Answers

array_filter to the rescue!

Before checking for min, remove the elements from your array which have Quantity set to 0.

echo min( array_column( array_filter($array,function($v) { 
return $v["Quantity"] > 0; }), 'Price' ) ); 

To make it more readable

$filtered=array_filter($array,function($v) { return $v["Quantity"] > 0; });
echo min( array_column( $filtered, 'Price' ) );

Fiddle

And an old-school version without all the closures

foreach($array as $v)
{
   if($v["Quantity"]>0 && (!$min || $v["Price"]<$min))
   $min=$v["Price"];
}

Fiddle

like image 110
Hanky Panky Avatar answered Dec 06 '25 05:12

Hanky Panky