PHP: Get the key of the highest value in an array.

This is a tutorial on how to get the key of the highest 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:

A PHP array containing integer values.

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 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:

In the PHP snippet above, we:

  1. Created an array of integer values.
  2. We got the largest number in the array by using PHP’s max function.
  3. After we figured out the largest number, we passed that value into the array_search function, which returns the first corresponding key.
  4. 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 for you if two or more elements contain the highest number:

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:

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 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

Perfect!

Facebook Comments