Home > Backend Development > PHP Tutorial > How to Find the Index of the Maximum Value in a PHP Array?

How to Find the Index of the Maximum Value in a PHP Array?

Susan Sarandon
Release: 2024-10-29 06:13:02
Original
858 people have browsed it

How to Find the Index of the Maximum Value in a PHP Array?

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
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template