How to Find the Index of the Highest Value in an Array?

Linda Hamilton
Release: 2024-10-29 01:46:30
Original
705 people have browsed it

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

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

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

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!