Get Maximum Value from string Key PHP Array

I want to get the maximum value from an array and could not found suitable single function from PHP vast function library.

I found max ($array1) function but it was not returning key’s value, which was important. Then I got second method after spending good amount of time. Actually I was also looking for most efficient function.
I think I could not found most efficient way of doing this. These are what I have found:

Get Max Value from Array having string key

Method 1:


<?php
// Sort array retaining key - value pair
asort($array1);
// last entry in array
$value = end($array1);
//  key of the last entry
$key = key ($array1);
echo "$key $value";
?>

Method 2:


<?php
//Return only maximum value of an array without their key
$value = max($array1);
?>
  • # 1 - by Tyron

    There is a trick you can do…

    Considering $array1 as the array which you wish the maximum key value, you can do:

    $array_max = array_keys($array1);
    $key_max = max($array_max);

    Just remembering: array_keys returns all the keys from the specified array in a new array. And the function max returns the maximum value of the array.
    Hope it helped.

  • # 2 - by Tyron

    There is a trick you can do…Considering $array1 as the array which you wish the maximum key value, you can do:$array_max = array_keys($array1);$key_max = max($array_max);Just remembering: array_keys returns all the keys from the specified array in a new array. And the function max returns the maximum value of the array.Hope it helped.

Comments are open for an year period. Please, write here on Facebook page.