Hightest value of an associative array

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);
}

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

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

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

Demo


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

Tags:

Php

Arrays