Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get min value in PHP array and get corresponding key

Tags:

arrays

php

min

I have an array:

Array ( [0] => 3 [1] => 0 )

I want PHP code that returns 1 because 1's value is the lowest.

How do I do this?

like image 274
Timothy Clemans Avatar asked Aug 15 '12 05:08

Timothy Clemans


3 Answers

This will return the first index that has the minimum value in the array. It is useful if you only need one index when the array has multiple instances of the minimum value:

$index = array_search(min($my_array), $my_array);

This will return an array of all the indexes that have the minimum value in the array. It is useful if you need all the instances of the minimum value but may be slightly less efficient than the solution above:

$index = array_keys($my_array, min($my_array));
like image 193
Trott Avatar answered Oct 14 '22 04:10

Trott


array_keys($array, min($array));
like image 22
KingKongFrog Avatar answered Oct 14 '22 04:10

KingKongFrog


http://php.net/manual/en/function.min.php

http://php.net/manual/en/function.array-search.php

$array = array( [0] => 3, [1] => 0);
$min = min($array);
$index = array_search($min, $array);

Should return 1

like image 3
HandiworkNYC.com Avatar answered Oct 14 '22 02:10

HandiworkNYC.com