PHP Get Highest Value from Array

I'm trying to get hold of the largest value in an array, while still preserving the item labels. I know I can do this by running sort(), but if I do so I simply lose the labels - which makes it pointless for what I need. Here's the array:

array("a"=>1,"b"=>2,"c"=>4,"d"=>5);

Any ideas?


Don't sort the array to get the largest value.

Get the max value:

$value = max($array);

Get the corresponding key:

$key = array_search($value, $array);

If you just want the largest value in the array use the max function. This will return the largest value, although not the corresponding key. It does not change the original array.

If you care about the the key you could then do

$key = array_search(max($array), $array)

(Edited to include @binaryLV's suggestion)


$a = array(10, 20, 52, 105, 56, 89, 96);
$b = 0;
foreach ($a as $key=>$val) {
    if ($val > $b) {
        $b = $val;
    }
}
echo $b;

You are looking for asort()


You could use max() for getting the largest value, but it will return just a value without an according index of array. Then, you could use array_search() to find the according key.

$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
$maxValue = max($array);
$maxIndex = array_search(max($array), $array);
var_dump($maxValue, $maxIndex);

Output:

int 5
string 'd' (length=1)

If there are multiple elements with the same value, you'll have to loop through array to get all the keys.

It's difficult to suggest something good without knowing the problem. Why do you need it? What is the input, what is the desired output?