Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get lowest value in array and include duplicates

Tags:

arrays

php

Say you have this array:

$users = [
    'a' => 2,
    'b' => 1,
    'c' => 1,
    'd' => 3
];

I need to get the keys with the lowest values. So in this case that would be b and c.

Currently doing it like this:

asort($users);

$lowestValue = array_values($users)[0];

foreach ($users as $k => $v)
    if ($v == $lowestValue)
        $lowestUsers[$k] = $v;

print_r($lowestUsers);

This works fine but is there a more shorter/efficient way of doing this?

like image 559
IMB Avatar asked Dec 22 '22 23:12

IMB


1 Answers

You can use array_keys to find the keys which have the lowest values in the array. If you pass array_keys a value as the second parameter it will return an array of all the keys which have that value in the array. Note that just using min is probably the simplest way to get the lowest value:

$lowestValue = min($users);
print_r(array_keys($users, $lowestValue));

Output:

Array (
  [0] => b
  [1] => c 
)

Demo on 3v4l.org

If you actually want the elements of the $users array which have the lowest value, you can take the output of array_keys and run it through array_intersect_key:

$lowestValue = min($users);
$lowestValueKeys = array_keys($users, $lowestValue);
$lowestUsers = array_intersect_key($users, array_flip($lowestValueKeys));
print_r($lowestUsers);

Although if that is the case it's simpler just to use array_filter:

$lowestValue = min($users);
$lowestUsers = array_filter($users, function ($v) use ($lowestValue) { return $v === $lowestValue; });
print_r($lowestUsers);

Output in both cases is

Array (
  [b] => 1
  [c] => 1 
)

Demo on 3v4l.org

like image 153
Nick Avatar answered Jan 07 '23 20:01

Nick