How to Get the Key of Max Value in Associative Array in PHP

Last Updated on January 6, 2021 by Roshan Parihar

In this tutorial, learn how to get the key of max value in an associative array in PHP. The short answer is: use the PHP max() to find the maximum value and array_search() to get the key of the max value.

You can also use the PHP foreach loop or PHP for loop to find the key of the maximum value. However, it requires to match the value with all the items if it is the maximum among them.

The associative array contains the items that have user-defined keys of string type. The keys are manually defined by the users for every value in the items. Let’s find out how to get the maximum key and its matching value pairs with the examples given below:

Get Key of Max Value in Associative Array Using PHP max() Function

To get the key of max value in an associative array, you can use the PHP max() and pass the array variable as the argument. It gives you the maximum value that you have to use and find its matching key using the PHP array_search(). See the example given below to learn the method:

Output

The max value is: 11, its key is: Cars

The above example showing the maximum value in the output with its matching key using PHP.

Using PHP Foreach Loop to Find the keys of Max Value

The foreach loop is useful to traverse through all the elements and find the key to the maximum value. It requires matching each value one-by-one to find which one is the maximum among them.

Output

The max value is: 11, its key is: Cars

The above example prints the maximum value in the output with its matching key using PHP.

Find the Maximum Item Using PHP For Loop

In addition to the above all methods, you can also use the PHP for loop to traverse through all the elements of an associative array. You have to match each value of the items to get the maximum out of them. Let’s find out the methods with the example given below:

Output

The max value is: 11, its key is: Cars

The above example showing the key for the matching maximum value. It uses the PHP if condition to match all the values and find the maximum among them. If the value matches and it is the maximum, it gets stored in a variable that gets printed in the output above.

All the methods given above are also useful to find the matching items in an associative array in PHP.

You May Also Like to Read

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.