14

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
3
  • 1
    Wow, what's with the downvotes? It's not a duplicate. Sure the answer was easy. I admit I should've known, but it still seems like a fair question to me. Commented Sep 11, 2013 at 7:51
  • 1
    @Ryan You got an upvote from me :) Commented Sep 11, 2013 at 7:52
  • Added the first strategy that came into my head to the question to help take off the off-topic hold. It seems silly now that I know about array_keys(), but this is what I was initially thinking when I asked the question. Would appreciate help (@Leri) reopening the question. Commented Sep 11, 2013 at 22:35

5 Answers 5

39

Try this:

echo min(array_keys($arr));
Sign up to request clarification or add additional context in comments.

2 Comments

This is an O(n) solution
I don't know what an O(n) is but one liners give me joy.
9

Try with

echo min(array_keys($arr));

min() is a php function that will return the lowest value of a set. array_keys() is a function that will return all keys of an array. Combine them to obtain what you want.

If you want to learn more about this two functions, please take a look to min() php guide and array_keys() php guide

Comments

1

use array_search() php function.

array_search(min($arr), $arr);

above code will print 200 when you echo it.

For echoing the value of lowest key use below code,

echo $arr[array_search(min($arr), $arr)];

Live Demo

2 Comments

@silkfire See Demo hit F9 or Press Run button..
@DipeshParmar It did not work with this array: $arr = array(100 => 'ganesh', 300 => 'foo', 200 => 'bar'); Returned 200 but should have been 100. Why the upvotes?
0

This also would be helpful for others,

<?php
//$arr = array(300 => 'foo', 200 => 'bar');
$arr = array("0"=>array('price'=>100),"1"=>array('price'=>50));

//here price = column name
echo minOfKey($arr, 'price');


function minOfKey($array, $key) {
    if (!is_array($array) || count($array) == 0) return false;
    $min = $array[0][$key];
    foreach($array as $a) {
        if($a[$key] < $min) {
            $min = $a[$key];
        }
    }
    return $min;
}

?>

Comments

-1
$arr = array(
300 => 'foo', 200 => 'bar'
);
$arr2=array_search($arr , min($arr ));
echo $arr2;

Comments

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.