Get max array key php

I had a situation where I needed to obtain the next available key in an array, which is the highest + 1.

For example, if the array is $data = ['1' => 'something, '34' => 'something else'], then I needed to calculate 35 to add a new element to the array that had a key higher than any of the others. In the case of an empty array I needed 1 as next available key.

This is the solution that worked:

$highest = 0;
foreach ($data as $idx => $dummy) {
    if ($idx > $highest) $highest = $idx;
}
$highest++;

It will work in all cases, empty array or not. If you only need to find the highest key rather than highest key + 1, delete the last line.

You will then get a value of 0 if the array is empty.

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:

Get max array key php

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:

  1. We created an array of integer values.
  2. We calculated 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 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 allof 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

Perfect!

(PHP 4, PHP 5, PHP 7, PHP 8)

maxFind highest value

Description

Alternative signature (not supported with named arguments):

max(array $value_array): mixed

Note:

Values of different types will be compared using the standard comparison rules. For instance, a non-numeric string will be compared to an int as though it were 0, but multiple non-numeric string values will be compared alphanumerically. The actual value returned will be of the original type with no conversion applied.

Caution

Be careful when passing arguments of different types because max() can produce unpredictable results.

Parameters

value

Any comparable value.

values

Any comparable values.

value_array

An array containing the values.

Return Values

max() returns the parameter value considered "highest" according to standard comparisons. If multiple values of different types evaluate as equal (e.g. 0 and 'abc') the first provided to the function will be returned.

If an empty array is passed, then false will be returned and an E_WARNING error will be emitted.

Examples

Example #1 Example uses of max()

<?php
echo max(23167);  // 7
echo max(array(245)); // 5

// The string 'hello' when compared to an int is treated as 0
// Since the two values are equal, the order they are provided determines the result

echo max(0'hello');     // 0
echo max('hello'0);     // hello

// Here we are comparing -1 < 0, so 'hello' is the highest value

echo max('hello', -1);    // hello

// With multiple arrays of different lengths, max returns the longest

$val max(array(222), array(1111)); // array(1, 1, 1, 1)

// Multiple arrays of the same length are compared from left to right
// so in our example: 2 == 2, but 5 > 4

$val max(array(248), array(251)); // array(2, 5, 1)

// If both an array and non-array are given, the array will be returned
// as comparisons treat arrays as greater than any other value

$val max('string', array(257), 42);   // array(2, 5, 7)

// If one argument is NULL or a boolean, it will be compared against
// other values using the rule FALSE < TRUE regardless of the other types involved
// In the below example, -10 is treated as TRUE in the comparison

$val max(-10FALSE); // -10

// 0, on the other hand, is treated as FALSE, so is "lower than" TRUE

$val max(0TRUE); // TRUE
?>

See Also

  • min() - Find lowest value
  • count() - Counts all elements in an array or in a Countable object

keith at bifugi dot com

6 years ago

The simplest way to get around the fact that max() won't give the key is array_search:

<?php
$student_grades
= array ("john" => 100, "sarah" => 90, "anne" => 100);
$top_student = array_search(max($student_grades),$student_grades); // john
?>

This could also be done with array_flip, though overwriting will mean that it gets the last max value rather than the first:

<?php
$grades_index
= array_flip($student_grades);
$top_student = $grades_index[max($student_grades)]; // anne
?>

To get all the max value keys:

<?php
$top_students
= array_keys($student_grades,max($student_grades)); // john, anne
?>

deoomen

2 months ago

Watch out after PHP 8.0!

Sample code:

<?php
echo max(0,'hello');
?>

Before PHP 8.0 will return int(0) but since PHP 8.0 above code returns string("hello")!!

volch5 at gmail dot com

8 years ago

max() (and min()) on DateTime objects compares them like dates (with timezone info) and returns DateTime object.
<?php
$dt1
= new DateTime('2014-05-07 18:53', new DateTimeZone('Europe/Kiev'));
$dt2 = new DateTime('2014-05-07 16:53', new DateTimeZone('UTC'));
echo
max($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T16:53:00+00:00
echo min($dt1,$dt2)->format(DateTime::RFC3339) . PHP_EOL; // 2014-05-07T18:53:00+03:00
?>

It works at least 5.3.3-7+squeeze17

costinu

10 years ago

max(null, 0) = null
max(0, null) = 0

marcini

13 years ago

Note that max() can compare dates, so if you write something like this:

<?php
$dates
= array('2009-02-15', '2009-03-15');
echo
max($dates);
?>

you will get: 2009-03-15.

Alex Rath

12 years ago

Notice that whenever there is a Number in front of the String, it will be used for Comparison.

<?php

  max

('7iuwmssuxue', 1); //returns 7iuwmssuxu
 
max('-7suidha', -4); //returns -4?>

But just if it is in front of the String

<?php

  max

('sdihatewin7wduiw', 3); //returns 3?>

ReVo_

8 years ago

Sometimes you could need to get the max from an array which looks like this:

<?php
$arrTest
= array(
    array(
"day" => 1, "b" => 10 ),
    array(
"day" => 2, "b" => 43 ),
    array(
"day" => 3, "b" => 2 ),
    array(
"day" => 4, "b" => -3 ),
    array(
"day" => 5, "b" => 4 ),
    array(
"day" => 6, "b" => -5 )
);
?>
all max functions i see around don't provide a way to get the max value of the values in (example) key "b"

<?php
function maxValueInArray($array, $keyToSearch)
{
   
$currentMax = NULL;
    foreach(
$array as $arr)
    {
        foreach(
$arr as $key => $value)
        {
            if (
$key == $keyToSearch && ($value >= $currentMax))
            {
               
$currentMax = $value;
            }
        }
    }

    return

$currentMax;
}
//                                            array       key
$value = maxValueInArray($arrTest, "b");?>

output: 43

ries at vantwisk dot nl

13 years ago

I had several occasions that using max is a lot slower then using a if/then/else construct. Be sure to check this in your routines!

Ries

michaelangel0 at mail.com

15 years ago

Matlab users and others may feel lonely without the double argument output from min and max functions.

To have the INDEX of the highest value in an array, as well as the value itself, use the following, or a derivative:

<?php
function doublemax($mylist){
 
$maxvalue=max($mylist);
  while(list(
$key,$value)=each($mylist)){
    if(
$value==$maxvalue)$maxindex=$key;
  }
  return array(
"m"=>$maxvalue,"i"=>$maxindex);
}
?>

johnphayes at gmail dot com

16 years ago

Regarding boolean parameters in min() and max():

(a) If any of your parameters is boolean, max and min will cast the rest of them to boolean to do the comparison.
(b) true > false
(c) However, max and min will return the actual parameter value that wins the comparison (not the cast).

Here's some test cases to illustrate:

1.  max(true,100)=true
2.  max(true,0)=true
3.  max(100,true)=100
4.  max(false,100)=100
5.  max(100,false)=100
6.  min(true,100)=true
7.  min(true,0)=0
8.  min(100,true)=100
9.  min(false,100)=false
10. min(100,false)=false
11. min(true,false)=false
12. max(true,false)=true

php at rijkvanwel dot nl

11 years ago

To get the largest key in an array:

<?php
$array
= array( 0 => 'first', 1=> 'second', /* ... */ 99 => 'nth' );
$max_key = max( array_keys( $array ) ); // 99
?>

sun at drupal dot org

11 years ago

Note that max() throws a warning if the array is empty:

<?php
$a
= array();
max($a);
// Warning: max(): Array must contain at least one element
?>

So make sure your data isn't empty.

info at osworx dot net

3 years ago

Be aware if a array like this is used (e.g. values from a shopping cart):
<?php
Array
(
    [
0] => 142,80
   
[1] => 39,27
   
[2] => 22,80
   
[3] => 175,80
)?>
The result will be: 39,27 and not - as expected - 175,80

So, to find the max value, use integer only like:
<?php
Array
(
    [
0] => 14280
   
[1] => 3927
   
[2] => 2280
   
[3] => 17580
)?>
and you will get the correct result: 17580

harmor

14 years ago

A way to bound a integer between two values is:

<?php
function bound($x, $min, $max)
{
     return
min(max($x, $min), $max);
}
?>

which is the same as:

<?php
$tmp
= $x;
if(
$tmp < $min)
{
   
$tmp = $min;
}
if(
$tmp > $max)
{
    
$tmp = $max;
}
$y = $tmp;
?>

So if you wanted to bound an integer between 1 and 12 for example:

Input:
<?php
$x
= 0;
echo
bound(0, 1, 12).'<br />';
$x = 1;
echo
bound($x, 1, 12).'<br />';
$x = 6;
echo
bound($x, 1, 12).'<br />';
$x = 12;
echo
bound($x, 1, 12).'<br />';
$x = 13;
echo
bound($x, 1, 12).'<br />';
?>

Output:
1
1
6
12
12

blackmac01 at gmail dot com

2 years ago

In response to: keith at bifugi dot com

If you want to find the specific key(s) that match the maximum value in an array where the values may be duplicated, you can loop through and perform a simple check:
<?php# Example Array
$a = array(
    
'key1' => 100,
    
'key2' => 90,
    
'key3' => 100,
    
'key4' => 90,
);
# First get the maximum value
$max = max($a);# Create a new array containing all keys which have the max value
foreach($a as $key => $val) {    
     if(
$val === $max) $b[] = $key;
}
# If you want a string list, just do this
$b = implode(' ', $b);
?>

This produces consistent results and will scale well in terms of performance, whereas functions like array_search and array_flip can lead to degraded performance when dealing with large amounts of data.

levim at php dot net

10 years ago

<?php
/**
* @param array $array
*
* @return int|null Returns the largest value of the array. Returns NULL if no
*     integers are found.
*/
function array_max_recursive(array $array) {
   
$max = NULL;
   
$stack = array($array);

    do {

$current = array_pop($stack );
        foreach (
$current as $value) {
            if (
is_array($value)) {
               
$stack[] = $value;
            } elseif (
filter_var($value, FILTER_VALIDATE_INT) !== FALSE) {
               
// max(NULL, 0) returns NULL, so cast it
               
$max = (int) max($max, $value);
            }
        }

    } while (!empty(

$stack));

    return

$max;
}
?>

- This function is not actually recursive, but fulfills the requirement that it works on sub-arrays.  I do this because PHP is not very good at recursion.  I also did it because I enjoy doing things this way. 
- It returns something of type int, never a string representation of an int. The exception is when you provide an array that does not contain any integers.  It will then return NULL.
- It ignores non-array, non-int values.

toon dot baeyens at gmail dot com

10 years ago

A little function for multi-dimensional arrays:
<?php
function amax($array){
    if(
is_array($array)){
        foreach(
$array as $key => $value){
           
$array[$key] = amax($value);
        }
        return
max($array);
    }else{
        return
$array;
    }
}
?>

Michael Blinn

3 years ago

Be careful using max() with objects, as it returns a reference not a new object.

<?php

$min_date

= date_create('2019-03-05');
$max_date = date_create('2019-03-06');$date_by_reference = max($min_date, $max_date);// $date_by_reference and $max_date are now the same objectecho '$max_date is ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-06'
echo '$date_by_reference is ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-06'date_add($date_by_reference, date_interval_create_from_date_string('1 days')); // Add 1 day to $date_by_reference, changes $max_date tooecho '$max_date is changed ' . date_format($max_date, 'Y-m-d') . PHP_EOL; // '2019-03-07'
echo '$date_by_reference is changed ' . date_format($date_by_reference, 'Y-m-d') . PHP_EOL; // '2019-03-07'?>

chris at candm dt org dt uk

1 year ago

A function to return the key of the max value of an array. For multiple max values, it will return the key of first. Change > to >= to get the last.

function array_max_key($arr) {
    $maxkey='';
    $maxval=false;
    array_walk($arr,
        function (&$cval,&$ckey) use(&$maxkey,&$maxval) {
            if ($maxval === false || $cval > $maxval) {
                $maxval = $cval;
                $maxkey = $ckey;
            }
        }
    );
    return $maxkey;
}

How to Get max value from array in PHP?

The max() function of PHP is used to find the numerically maximum value in an array or the numerically maximum value of several specified values. The max() function can take an array or several numbers as an argument and return the numerically maximum value among the passed parameters.

How do you find the max value in an array?

To get the index of the max value in an array:.
Get the max value in the array, using the Math. max() method..
Call the indexOf() method on the array, passing it the max value..
The indexOf method returns the index of the first occurrence of the value in the array or -1 if the value is not found..

What is Array_map function in PHP?

The array_map() is an inbuilt function in PHP and it helps to modify all elements one or more arrays according to some user-defined condition in an easy manner. It basically, sends each of the elements of an array to a user-defined function and returns an array with new values as modified by that function.

How do you find array keys?

The array_keys() function is used to get all the keys or a subset of the keys of an array. Note: If the optional search_key_value is specified, then only the keys for that value are returned. Otherwise, all the keys from the array are returned. Specified array.