This is a tutorial on how to get the key of the largest value in a PHP array.
To do this, we will be using a combination of PHP’s max and array_search functions.
Let’s say that we have the following PHP array:
As you can see in the outputted var_dump above, we have an array that contains 6 integer numbers. We can see just by looking at it that 23 is the highest number in the array and that it is located at index 1.
However, how do we figure out the array key using PHP while maintaining the key-to-value associations?
Take a look at the following example:
//Array of integers. $arr = array( 1, 23, 6, 12, 19, 12 ); //Find the highest value in the array //by using PHP's max function. $maxVal = max($arr); //Use array_search to find the key that //the max value is associated with $maxKey = array_search($maxVal, $arr); //Print it out. echo 'Max value is ' . $maxVal . ' at array index: ' . $maxKey;
In the PHP snippet above:
- We created an array of integer values.
- We calculated the largest number in the array by using PHP’s max function.
- After we figured out the largest number, we passed that value into the array_search function, which returns the first corresponding key.
- Finally, we printed out the result.
If you run the code above yourself, you should see the following output:
Max value is 23 at array index: 1
The only problem with this method is that array_search will return the first key.
This might become an issue if two or more elements contain the highest number:
$arr = array( 1, 23, 6, 23, 23, 12, 19, 12 );
As you can see above, there are three elements that contain the highest number: 1, 3 and 4.
If we use the method above on this array, the result will still be 1. It will not return 1, 3 and 4. This is because array_search will always return the first key that it finds.
Find ALL array keys that contain the max value.
If you need to find all of the array keys that contain the highest value, then you will have to take the following approach:
//Array of integers. $arr = array( 1, 23, 6, 23, 23, 12, 19, 12 ); //Get the max value in the array. $maxVal = max($arr); //Get all of the keys that contain the max value. $maxValKeys = array_keys($arr, $maxVal); //Print it out. echo 'Max value ' . $maxVal . ' exists at: ' . implode(", ", $maxValKeys);
This is similar to the other method that we used above.
However, this time we searched the array by using the PHP function array_keys. This function will return an array with all of the keys that contain the value we passed through as the second parameter.
If you run the snippet above, you should end up with the following result:
Max value 23 exists at: 1, 3, 4