3
$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?

3
  • 2
    Are you trying to find the lowest price where quantity is greater than 0? Commented Dec 13, 2016 at 5:02
  • @ObjectManipulator Yes, exactly. Commented Dec 13, 2016 at 5:05
  • Array column is a waste of memory. Loop through the array Commented Dec 13, 2016 at 5:16

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

You need to filter out the array index with 0 quantity using array_filter().

$filtered_array = array_filter($array, function($v) {
    return $v['Quantity'];
});

echo min( array_column( $filtered_array, 'Price' ) );

Comments

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

    $price=array();

    for($i=0; $i<count($array);$i++){
      $price[$i]=$array[$i]['Price'];  
    }

    echo  min($price); //70

Comments

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.