If I have an array like so (it could be any combination of numbers):
$arr = array(1, 2, 4, 2, 3, 5, 4, 2, 1);
I want to move all the elements that equal 4 to the end of the array, while preserving the order of the other elements, so ideally my resulting array would be:
1, 2, 2, 3, 5, 2, 1, 4, 4
I thought I could acheve this by using a sort function:
uasort($arr, function($a, $b){
return $b == 4 ? -1 : 1;
});
Which moves the "4" elements to the end, but ruins the order of the other elements, this is my result with the above code:
2, 3, 1, 2, 5, 2, 1, 4, 4
How should my sorting handler function look? / Is there a better way to achieve this than sorting the array?
Note; I want to preserve my array keys (hence uasort
)