Won't the call to array_filter cause a close to O(n ^ 2) time complexity? In principle it should be possible to do this operation in O(n), no? Could it be done without losing generality? Maybe one would need to pass a counter $i around while looping and making recursive calls?
I'm asking because I'm facing the same problem.