简体   繁体   中英

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

试试这个:

echo min(array_keys($arr));

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

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM