How to return the minimum key to an array?

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

Given an array:

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

How to return the minimum key ( 200 )?

Here is one approach, but I have to imagine 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 
+7
sorting arrays php
source share
5 answers

Try the following:

 echo min(array_keys($arr)); 
+22
source share

Try

 echo min(array_keys($arr)); 

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

If you want to know more about these two functions, see the min() php guide and array_keys() php guide

+7
source share

use array_search() php function.

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

The above code will print 200 when you echo it.

To repeat the value of the lower key, use the code below,

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

Live demo

+1
source share
 $arr = array( 300 => 'foo', 200 => 'bar' ); $arr2=array_search($arr , min($arr )); echo $arr2; 
0
source share

It would also be beneficial 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; } ?> 
0
source share

All Articles