How do you find the index of the highest value in a numerical array?

Barbara Streisand
Release: 2024-10-31 03:50:30
Original
687 people have browsed it

How do you find the index of the highest value in a numerical array?

Extracting Index of Highest Value in an Array

Given an array with numerical values, determining the index of the element with the highest value can be useful in various programming scenarios. To achieve this, a pragmatic approach is to leverage built-in array functions.

One effective solution is to utilize the max() function, which returns the highest value within the array. To retrieve the index associated with this maximum value, we can combine it with the array_keys() function.

Consider the following array:

Array (
    [11] => 14
    [10] => 9
    [12] => 7
    [13] => 7
    [14] => 4
    [15] => 6
)
Copy after login

To obtain the index of the highest value (14), we can employ the following code:

<code class="php">$maxs = array_keys($array, max($array));</code>
Copy after login

This solution assigns the array keys corresponding to the maximum value (11) to the $maxs variable. It's worth noting that in cases where there are multiple keys associated with the highest value, this approach will return an array containing all of them.

If obtaining only one index among all is desired, it can be retrieved using the following syntax:

<code class="php">$maxIndex = $maxs[0];</code>
Copy after login

The above is the detailed content of How do you find the index of the highest value in a numerical 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!