Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I return the minimum key in an array?

Is there an equivalent min() for the keys in an array?

Given the array:

$arr = array(300 => 'foo', 200 => 'bar');

How can I return the minimum key (200)?

Here's one approach, but I have to imagine there's an easier way.

function minKey($arr) {
    $minKey = key($arr);
    foreach ($arr as $k => $v) {
        if ($k < $minKey) $minKey = $k;
    }
    return $minKey;
}
$arr = array(300 => 'foo', 200 => 'bar');
echo minKey($arr); // 200
like image 883
Ryan Avatar asked Sep 11 '13 07:09

Ryan


1 Answers

Try this:

echo min(array_keys($arr));
like image 186
silkfire Avatar answered Sep 17 '22 15:09

silkfire