3

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?!

2 Answers 2

5

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);

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

Comments

-1

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]);

2 Comments

Causes E_STRICT errors: only variables should be passed by reference (ie. to array_pop). Additionally, your code relies on an associative array being in a specific order.
@Kolink, aaahhhhh!!!!, I tried it on codepast only and initially seemed to work, we (I) never stop learning. Thanks for comment!

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.