Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

usort changing Array's order

Tags:

php

usort

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?

like image 618
Asaf Avatar asked Sep 02 '11 13:09

Asaf


People also ask

How do you change the order of an array?

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.

Does sort change the original array?

The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.

Does sort change in place?

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.

Is PHP Usort stable?

Sorting functions in PHP are currently unstable, which means that the order of “equal” elements is not guaranteed.


1 Answers

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.

like image 151
phihag Avatar answered Oct 04 '22 05:10

phihag