Need to get specific indices from PHP array
I created an array in PHP that contains bucnh of unix timestamps.
I am trying to create a function that will return an array containing the indices of the 3 largest numbers in this array.
For example, if the largest numbers are located at indices 3.5 and 8
And if the largest one is 5, the second largest is 8, and the smallest one is number 3, I want the order to contain the values (5,8,3).
And honestly, I don't know how to do it. Does anyone know how to do this?
source to share
You can use asort to sort the array and maintain the index, then use slice along with the 4th parameter, again to maintain the index to grab the top x number of elements you are after, and finally use array_keys .
This might be a faster way, but just to show that there are many PHP array functions out there to help you achieve the effect you are looking for.
source to share
Simon posted a simple and probably good enough way to do it.
Another option, only if you have a really large array, is to scan through the array and keep track of the indices of the three highest values you see. It's O (n), but (especially because it's interpreted by PHP code and not by a compiled inline function) it's probably slower for everything but the largest array.
source to share
In pseudocode:
function select(list[1..n], k)
for i from 1 to k
maxIndex = i
maxValue = list[i]
for j from i+1 to n
if list[j] > maxValue
maxIndex = j
maxValue = list[j]
swap list[i] and list[maxIndex]
return list[k]
newarray[] = select(array, 1);
newarray[] = select(array, 2);
newarray[] = select(array, 3);
source to share