Reorder Array

I have a usort function with one line: return 0.
I tried using it in an array of stdClass objects and it changed the value of their order, how is this possible?

+4
source share
2 answers

The alleged property is called stability : a stable sorting algorithm will not change the order of equal elements.

The php sort functions are not stable (since unstable sorts can be a little faster). From the usort documentation :

If two members are compared as equal, their order in the sorted array is undefined.

If you need a stable sorting algorithm, you must implement it yourself .

+8
source

This is because this function means "I really don't care how they are sorted, they are equal to me." With this simple example, I get an inverse array:

 function sortaaa($a,$b) {return 0;} $array = array(1,2,3,4,5); usort($array,"sortaaa"); var_dump($array); //prints array(5) { [0]=> int(5) [1]=> int(4) [2]=> int(3) [3]=> int(2) [4]=> int(1) } 

So, it looks like PHP is accessing the array in reverse order in the usort function. So, look at the usort manual claims that

If two members are compared as equal, their order in the sorted array is undefined.

+1
source

All Articles