Determining the Index of Maximum Value in an Array
Retrieving the index of the maximum value in an array is a common task in programming. Consider an array with numerical values, such as:
[11] => 14 [10] => 9 [12] => 7 [13] => 7 [14] => 4 [15] => 6
Solution:
To obtain the index of the highest value in the array, we utilize the built-in PHP function array_keys(). This function takes two arguments: the array and the target value. In our case, we are interested in the maximum value. By combining this function with the max() function, we can determine the index(es) associated with the highest value.
<code class="php">$maxs = array_keys($array, max($array));</code>
The result, stored in the $maxs array, contains all indexes that correspond to the maximum value. If you only require a single index, you can access it with $maxs[0].
Note:
Using this approach, you obtain every index related to the maximum value. In cases where there are multiple occurrences of the maximum value, all corresponding indexes will be included in the $maxs array.
The above is the detailed content of How to Find the Index of the Maximum Value in a PHP Array?. For more information, please follow other related articles on the PHP Chinese website!