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

4
  • if you run it through rsort(), it will always be the first one :D
    – Kevin Kopf
    Commented Feb 24, 2018 at 18:33
  • @AlexKarshin but it's O(n log(n)) where maximum of array is just O(n) Commented Feb 24, 2018 at 18:34
  • you can use max() and array_keys to get the position of highest value check this link: stackoverflow.com/questions/1461348/…
    – Madhu
    Commented Feb 24, 2018 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
    Commented Feb 24, 2018 at 18:39

1 Answer 1

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.

0