I have a usort function with a single line: return 0.
I tried to use it on an Array of stdClass objects, and it changes
their order, how is that possible?
sort() - sort arrays in ascending order. rsort() - sort arrays in descending order. asort() - sort associative arrays in ascending order, according to the value. ksort() - sort associative arrays in ascending order, according to the key.
The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.
A side effect of the sort method is that it changes the order of the elements in the original array. In other words, it mutates the array in place.
Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.
The property you assume is called stability: A stable sorting algorithm will not change the order of elements that are equal.
php's sorting functions are not stable (because non-stable sorts may be slightly faster). From the documentation of usort
:
If two members compare as equal, their order in the sorted array is undefined.
If you want a stable sorting algorithm, you must implement it yourself.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With