2

So i want to find the position of the highest number in this array.

$numbers = array($n1, $n2, $n3, $n4, $n5, $n6, $n7, $n8, $n9, $n10);

How do i do that? Thanks

divibisan
  • 11,659
  • 11
  • 40
  • 58
  • if you run it through `rsort()`, it will always be the first one :D – Kevin Kopf Feb 24 '18 at 18:33
  • @AlexKarshin but it's O(n log(n)) where maximum of array is just O(n) – Daniel Krom Feb 24 '18 at 18:34
  • you can use `max()` and `array_keys` to get the position of highest value check this link: https://stackoverflow.com/questions/1461348/return-index-of-highest-value-in-an-array – Madhu Feb 24 '18 at 18:36
  • @DanielKrom it was a joke, `rsort()` doesn't maintain the key association :) So the key of the highest value would always be `0` :) – Kevin Kopf Feb 24 '18 at 18:39

1 Answers1

6

max() can receive an array as a parameter, so with:

$numbers = array($n1, $n2, $n3, $n4, $n5, $n6, $n7, $n8, $n9, $n10);
$max = max($numbers);

$max will have the highest number. Then, use array_search() to get the position:

$pos = array_search($max, $numbers);
echo "Position: ".$pos; // Position: 5

Demo

Note that the position will be the index, so if you want the "real" position, subtract one.

ishegg
  • 9,685
  • 3
  • 16
  • 31