Search code examples
phparrayssortingkeyslice

Get indexes of 3 largest values in a flat array


I have an array in PHP which holds a bunch of unix timestamps.

As a simplified example, here is an array of 10 values.

$array = [
  1510790277,
  1586522582,
  1572272336,
  1650049585,
  1591332330,
  1698088238,
  1646561226,
  1639050043,
  1652067570,
  1548161804,
];

I need to produce an array containing the indexes of the 3 largest numbers in that array.

From the sample array, I would expect a result of [5, 8, 3] -- in that order.


Solution

  • You could use asort to sort the array and maintain index and then use slice along with the 4th parameter, again to maintain the index, to grap the top x number of elements you are after, and finally use array_keys.

    There may well be a quicker way, but it's just to show there are plenty of PHP array functions to help you achieve the effect you're looking for.