PHP array_multisort does not sort second array correctly
Here is my code:
$numbers = array(10, 100, 100, 0);
$names = array("Alex", "Jane", "Amanda", "Debra");
array_multisort($numbers, $names);
print_r($numbers);
print_r($names);
The above code outputs:
Array
(
[0] => 0
[1] => 10
[2] => 100
[3] => 100
)
Array
(
[0] => Debra
[1] => Alex
[2] => Amanda
[3] => Jane
)
Why is the sorting of the second array wrong? If this is correct, can anyone explain how this is correct?
Thank.
source to share
Yes, that's right. You are using PHP array_multisort function incorrectly. It will not sort both arrays, but it will sort the first array, and the second array will be ordered in the same order as the first array.
$ numbers Before sorting:
(
[0] => 10
[1] => 100
[2] => 100
[3] => 0
)
After sorting:
(
[0] => 0 (position before sorting - 3rd)
[1] => 10 (position before sorting - 0)
[2] => 100 (position before sorting - 2 or 1)
[3] => 100 (position before sorting - 2 or 1)
)
So the second array will not be sorted, but will get its elements according to the first array.
(
[0] => Debra --in first array 3rd element has moved to 0th position
[1] => Alex -- in first array 0th element has moved to 1st position
[2] => Amanda -- in first array 2nd element has moved to 2nd position
[3] => Jane -- in first array 1st element has moved to 3rd position
)
source to share
This is expected behavior array_multisort
. The first array is sorted and the second array is overridden, so its values continue to match the same values in the first array. Note that when the first array has equal values (two 100
s), the values of the second array are sorted internally (therefore Amanda
preceded by Jane
).
If you want to sort the two arrays yourself, you can just use two calls sort
.
source to share