1

Possible Duplicate:
Return index of highest value in an array

How can i return all the index of the max value.. for example a have this array that contains grades of students

$grade = array(                       
        "anna"  => "5",
        "lala"=>"7",
        "eni"=>"7",

i want to return the names of the student who have the max grade in this case should print: lala eni

Community
  • 1
  • 1
romina
  • 21
  • 1
  • 2
  • 1
    [what have you tried so far](http://whathaveyoutried.com)? – Ayush Dec 10 '12 at 13:46
  • On very first search -> http://stackoverflow.com/questions/1461348/return-index-of-highest-value-in-an-array – Rikesh Dec 10 '12 at 13:47
  • I found a same question with a perfect answer for you : http://stackoverflow.com/questions/1461348/return-index-of-highest-value-in-an-array – Ladineko Dec 10 '12 at 13:53

4 Answers4

2

You can use max() in order to find the higest value and then do array_keys() over it.

http://php.net/manual/en/function.max.php http://php.net/manual/en/function.array-keys.php E.g.

$grade = array(                       
    "anna"  => "5",
    "lala"=>"7",
    "eni"=>"7",

$max = max($grade); // $max == 7
array_keys($grade, $max); 
tehsis
  • 1,602
  • 2
  • 11
  • 15
  • Awesome, didn't know max() did this out of the box.. Thanks for everyone pointing to other answers, but this comes up on top in Google when we search "max associative array php".. Thank you! – Robert Sinclair Jul 28 '16 at 14:54
1

it looks like a school exercise ... Ok, you can write something like that:

$maxInd = -1;
foreach($grade as $name => $ind) {
    if($ind > $maxInd) {
        $maxInd = $ind;
        $maxRes = array();
    }
    if($ind == $maxInd) {
        $maxRes[] = $name;
    }
}
return "The highest names are " . implode(', ',$maxRes);

please, let me know if it works!

0

you can do sth. like this:

$inversed = Array();        
$highGrade = 0;
foreach ($grade AS $student=>$grade){
  if (isset($inversed[$grade]))
    $inversed[$grade][] = $student;
  else
    $inversed[$grade] = Array($student);

  if ($grade > $highGrade) $highGrade = $grade;
}


print_r($inversed[$highGrade]);
dognose
  • 20,360
  • 9
  • 61
  • 107
0
<?php
$grade = array(  
    "atest" => 6,                     
        "banna"  => "5",
        "lala"=>"7",
        "eni"=>"7");
asort($grade);
$reverse = array_reverse($grade);
$prev_val='';
$counter = 0;
foreach($reverse as $key=>$value)
{
if((($counter==1)&&($value==$prev_val))||($counter==0))
{
echo $key."->".$value."<br/>";
$prev_val = $value;
$counter++;
}
}

?>

I have added one more element to the array to clear your doubt.

Ruchira Shree
  • 163
  • 10