Home > Article > Backend Development > How to Find the Index of the Highest Value in an Array?
How to Retrieve the Index of the Highest Value in an Array
Given an array with values like the one shown below, it's common to encounter the need to identify the index of the highest value within that array. For example, for the array below, you would want to know that the highest value, 14, is found at index 11.
Array ( [11] => 14 [10] => 9 [12] => 7 [13] => 7 [14] => 4 [15] => 6 )
Solution:
To determine the index of the highest value in an array, you can utilize the following solution:
<code class="php">$maxs = array_keys($array, max($array));</code>
This code retrieves the keys of the elements with the highest value in the array. By default, it returns all such keys into the $maxs array.
Note:
Depending on the needs of your specific application, you may only be interested in retrieving a single key associated with the highest value. If that's the case, simply use the following code:
<code class="php">$maxs = array_keys($array, max($array))[0];</code>
This variation ensures that you only retrieve the first matching key, which will correspond to the index of the highest value.
The above is the detailed content of How to Find the Index of the Highest Value in an Array?. For more information, please follow other related articles on the PHP Chinese website!