PHP Array Exercises : Get the index of the highest value in an associative array
31. Get Index of Highest Value in Associative Array
Write a PHP program to get the index of the highest value in an associative array.
Sample Solution:
PHP Code:
<?php
// Define an associative array $x with key-value pairs
$x = array(
'value1' => 3021,
'value2' => 2365,
'value3' => 5215,
'value4' => 5214,
'value5' => 2145);
// Reset the internal pointer of the array to the first element (optional step)
reset($x);
// Sort the array in descending order based on values, preserving keys
arsort($x);
// Get the key of the maximum (first) value in the sorted array
$key_of_max = key($x);
// Display the index (key) of the highest value in the original array
echo "Index of the highest value : " . $key_of_max . "\n";
?>
Output:
Index of the highest value : value3
Flowchart:

For more Practice: Solve these Related Problems:
- Write a PHP script to traverse an associative array and output the key corresponding to the maximum value.
- Write a PHP function to identify and return the index of the highest value in an associative array using a custom comparison.
- Write a PHP program to sort an associative array by values and then retrieve the key of the top element.
- Write a PHP script to implement a loop that compares values in an associative array and tracks the key of the maximum entry.
PREV : Create Letter Range with Arbitrary Length.
NEXT : Get File Extension.
PHP Code Editor:
Contribute your code and comments through Disqus.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.