Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Get minimum value of a key in array of arrays

Tags:

php

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

like image 684
Lord Aelx Avatar asked Dec 31 '25 19:12

Lord Aelx


1 Answers

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

like image 171
Niet the Dark Absol Avatar answered Jan 03 '26 10:01

Niet the Dark Absol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!