Lord Aelx
Lord Aelx

Reputation: 49

PHP Get minimum value of a key in array of arrays

I have an array like this:

$array = array(
    array('id' => 1, 'quantity' => 10),
    array('id' => 2, 'quantity' => 25),
    array('id' => 3, 'quantity' => 38),
    ...
);

I want to find the array contains minimum of quantity. How can I do it simply in one two lines of code?! (I prefer to use PHP functions)

Also if the variable is an Object, Does it make any difference?!

Upvotes: 3

Views: 1658

Answers (2)

Alex Ball
Alex Ball

Reputation: 4484

For the min value:

$min = min(array_map("array_pop",$array));
print_r($min);

For the key:

$min = array_keys(array_map("array_pop",$array), min(array_map("array_pop",$array)));
print_r($min[0]);

Upvotes: -1

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324810

Like this:

usort($array,function($a,$b) {return $a['quantity']-$b['quantity'];});
return $array[0];

If needed, create a copy of the original array using $copy = array_slice($array,0);

Upvotes: 5

Related Questions