Hightest value of an associative array

Is there any easy way to get the hightest numeric value of an associative array?

$array = array(
    0 => array(
        'key1' => '123',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    ),
    1 => array(
        'key1' => '124',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    ),
    2 => array(
        'key1' => '125',
        'key2' => 'values we',
        'key3' => 'do not',
        'key4' => 'care about'
    )
);

AwesomeFunction($array, 'key1'); // returns 2 ($array key)

Please be kind since this question was written with a phone. Thanks.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

PHP 5.5 introduced array_column() which makes this much simpler:

echo max(array_column($array, 'key1'));

Demo

Solution 2

If you know your data will always be in that format, something like this should work.

function getMax( $array )
{
    $max = 0;
    foreach( $array as $k => $v )
    {
        $max = max( array( $max, $v['key1'] ) );
    }
    return $max;
}

Solution 3

@ithcy – extension to that will work with any size array

function getMax($array) {
    if (is_array($array)) {
        $max = false;
        foreach($array as $val) {
            if (is_array($val)) $val = getMax($val);
            if (($max===false || $val>$max) && is_numeric($val)) $max = $val;
        }
    } else return is_numeric($array)?$array:false;
    return $max;
}

I think
(returns false when there are no numeric values are found)

Solution 4

This one is inspired by ithcy example, but you can set the key to look up.
Also, it returns both the min and max values.

function getArrayLimits( $array, $key ) {
    $max = -PHP_INT_MAX;
    $min = PHP_INT_MAX;
    foreach( $array as $k => $v ) {
        $max = max( $max, $v[$key] );
        $min = min( $min, $v[$key] );
    }
    return Array('min'=>$min,'max'=>$max);
}

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply