Is there a min() equivalent for keys in an array?
min()
Given an array:
$arr = array(300 => 'foo', 200 => 'bar');
How to return the minimum key ( 200 )?
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
Try the following:
echo min(array_keys($arr));
Try
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.
array_keys()
If you want to know more about these two functions, see the min() php guide and array_keys() php guide
use array_search() php function.
array_search()
array_search(min($arr), $arr);
The above code will print 200 when you echo it.
echo
To repeat the value of the lower key, use the code below,
echo $arr[array_search(min($arr), $arr)];
Live demo
$arr = array( 300 => 'foo', 200 => 'bar' ); $arr2=array_search($arr , min($arr )); echo $arr2;
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; } ?>