$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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With