tuxnani
tuxnani

Reputation: 3864

How to deal with an array of equal values and max function?

In PHP, max() returns the highest value in an array or the greatest value among inputs. If we have two or more equally greatest values, how to deal with that situation? eg

$arr = array("a"=>1,"b"=>10, "c"=>10);

now, what should max($arr), return. Ideally it returns the first encountered highest value, b. What if I want both b and c as result?

Upvotes: 1

Views: 1405

Answers (2)

Niko
Niko

Reputation: 26730

If you have the highest value in that array (that is, what max() returns), you can just search for all occurrences of that value in the array:

$arrOfKeys = array_keys($arr, max($arr));

Upvotes: 9

DaveRandom
DaveRandom

Reputation: 88707

max() returns the maximum value, not the array key it is associated with. It will simply return (int) 10 in the example you give.

If you want a list of the keys that have the maximum value you could do something like this:

$max = max($array);
$maxKeys = array();
foreach ($array as $key => $val) {
  if ($val == $max) {
    $maxKeys[] = $key;
  }
}

print_r($maxKeys);
/*
  Array
  (
      [0] => b
      [1] => c
  )
*/

Upvotes: 3

Related Questions