15

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?

mickmackusa
  • 43,625
  • 12
  • 83
  • 136
Timothy Clemans
  • 1,711
  • 3
  • 16
  • 26

4 Answers4

43

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:

$indexes = array_keys($my_array, min($my_array));
Trott
  • 66,479
  • 23
  • 173
  • 212
23
array_keys($array, min($array));
KingKongFrog
  • 13,946
  • 21
  • 75
  • 124
  • 2
    It would be better if you write a little bit more, perhaps what you do and why. Maybe you can also link to an official documentation. – Martin Nov 12 '17 at 14:58
  • 1
    php.net's doc: "… If a `search_value` is specified, then only the keys for that value are returned …". An array containing "indexes" of matched items would be returned hence. – poige Jun 21 '20 at 06:14
3

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

HandiworkNYC.com
  • 10,914
  • 25
  • 92
  • 154
1

The below example would help you.

$values=array(3,0,4,2,1);
$min_value_key=array_keys($values, min($values));
echo $min_value_key;

Hope this helps.

User 99x
  • 1,011
  • 1
  • 13
  • 39