62

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?

Jamie McElwain
  • 633
  • 2
  • 7
  • 7

17 Answers17

171

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);
Karoly Horvath
  • 94,607
  • 11
  • 117
  • 176
  • Why not `array_max()` dear php. Note that this function will not return an int if your values are of the string type. (even if they contain integers). So best to do $value = (int) max($array); – COil Nov 13 '18 at 17:00
  • 5
    max($array) is not going to work if two keys have the same max value. – anoldermark Apr 25 '19 at 17:03
  • you know the max value, so loop through array to get matching IDs – anoldermark Oct 22 '19 at 13:54
25

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)

borrible
  • 17,120
  • 7
  • 53
  • 75
6
$a = array(10, 20, 52, 105, 56, 89, 96);
$b = 0;
foreach ($a as $key=>$val) {
    if ($val > $b) {
        $b = $val;
    }
}
echo $b;
anthony sottile
  • 61,815
  • 15
  • 148
  • 207
Rakesh
  • 69
  • 1
  • 1
5

You are looking for asort()

Jacob
  • 41,721
  • 6
  • 79
  • 81
  • 1
    If you don't need the whole array sorted, use one of the gazillion other answers obviously ;) But mentioning sort() made me think you phrased your question wrong. – Jacob Jul 13 '11 at 09:43
  • Jacob is right - doing an asort will reorder the array lowest to highest maintaining keys...then do a foreach and the $key=>$value from that will be set to the highest pair after the foreach completes..so you have the highest one right there - the key and the value... – gman_donster Aug 23 '19 at 00:06
  • If we use sort() or asort() it may lead to time complexity with n nodes – chandru Nov 15 '21 at 16:35
  • @chandru Which is good or bad? – Syed M. Sannan Aug 05 '22 at 11:31
  • 1
    @Stranger ...which is not necessary for this question/page. A loop (instead of sorting) will be "linear" and therefore will boast better performance. – mickmackusa Jan 10 '23 at 00:50
  • @mickmackusa I see – Syed M. Sannan Jan 10 '23 at 11:52
5

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?

binaryLV
  • 9,002
  • 2
  • 40
  • 42
1

greatestValue=> try this its very easy

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

}
echo $c;
Ashish Pathak
  • 827
  • 8
  • 16
1
$ee = array('a' => 50, 'b' => 25, 'c' => 5, 'd' => 80, 'e' => 40, 'f' => 152, 'g' => 45, 'h' => 28);
$Acurr = '';
$Amax = 0;

foreach($ee as $key => $value) {
    $Acurr = $value;    

    if($Acurr >= $Amax) {
        $Amax = $Acurr; 
    }
}

echo "greatest number is $Amax";
Djave
  • 8,595
  • 8
  • 70
  • 124
1

Try it.

$data = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); $maxKey = current(array_keys($data, max($data))); var_dump($maxKey);

Yin Yong
  • 11
  • 1
  • 3
    Welcome to Stack Overflow. Eight year old questions with fifteen existing answers require more than a code only answer. It is very important to point out what new aspect of the question your answer addresses. All answers can generally benefit from explaining how and why they work as well. – Jason Aller Jun 06 '20 at 18:39
0
$abc=array("a"=>1,"b"=>2,"c"=>4,"e"=>7,"d"=>5);
/*program to find max value*/
$lagest = array();
$i=0;
foreach($abc as $key=>$a) {
    if($i==0) $b=$a;
    if($b<$a) {
        $b=$a;
        $k=$key;
    }
    $i++;
 }
 $lagest[$k]=$b;
 print_r($lagest);
Spudley
  • 166,037
  • 39
  • 233
  • 307
0
<?php 
$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5); 

foreach ($array as $key => $value) {
   if ($value >= $max) 
    $max = $key;     
}
echo " The array in largest number :".$max."<br/>";
?> 
Hanifeoglu
  • 49
  • 2
  • 11
0

Find highest number, including negative:

return max([abs(max($array)),abs(min($array))]);
Jason Mullings
  • 850
  • 14
  • 10
0
// assuming positive numbers

$highest_key;
$highest_value = 0;
foreach ($array as $key => $value) {
    if ($value > $highest_value) {
        $highest_key = $key;
    }
}

// $highest_key holds the highest value
erenon
  • 18,838
  • 2
  • 61
  • 93
-1

You need to use by ksort(array("a"=>1,"b"=>2,"c"=>4,"d"=>5)); for more info: http://www.w3schools.com/php/php_arrays_sort.asp

-1

Here a solution inside an exercise:

function high($sentence)
{
    $alphabet = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'ñ', 'o', 'p', 'q', 'r', 't', 'u', 'v', 'w', 'x', 'y', 'z'];
    $alphabet = array_flip($alphabet);

    $words = explode(" ", $sentence);

    foreach ($words as $word) {
        $letters = str_split($word);
        $points = 0;
        foreach ($letters as $letter)
            $points += $alphabet[$letter];
        $score[$word] = $points;
    }

    $value = max($score);
    $key = array_search($value, $score);

    return $key;
}

echo high("what time are we climbing up the volcano");
Erich García
  • 1,648
  • 21
  • 30
-1

asort() is the way to go:

$array = array("a"=>1,"b"=>2,"c"=>4,"d"=>5);
asort($array);
$highestValue       = end($array);
$keyForHighestValue = key($array);
Stefan Gehrig
  • 82,642
  • 24
  • 155
  • 189
-1

Find largest number without using built-in functions in PHP

<?php
    $array = array(1,2,3);
    $flag = 0;
    foreach($array as $key=>$val){
        if($val > $flag){
           $flag = $val;
        }
        echo "Max value with each iteration: ".$flag."<br/>";
    }
    echo "Final max value: ".$flag;
    ?>
Billu
  • 2,733
  • 26
  • 47
-2

Try using asort().

From documentation:

asort - Sort an array and maintain index association

Description:

bool asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )

This function sorts an array such that array indices maintain their correlation with the array elements they are associated with. This is used mainly when sorting associative arrays where the actual element order is significant.

Qantas 94 Heavy
  • 15,750
  • 31
  • 68
  • 83
SergeS
  • 11,533
  • 3
  • 29
  • 35