Let me tell you from the start: I know about the sort flags of this function. When I use SORT_STRING it works well, but the default flag SORT_REGULAR works weird, or doesn't work at all.
Consider an array like below.
$arr = [
'27a' => 'foo',
'27b' => 'foo',
'27c' => 'foo',
'27' => 'foo',
];
When I try to sort using ksort, it gives an array without being sorted in any obvious logic.
ksort($arr);
print_r($arr);
// this prints
Array
(
[27a] => foo
[27] => foo
[27b] => foo
[27c] => foo
)
As one could say the keys are neither numerically nor alphanumerically nor naturally sorted. Even more strangely, when I change the order of the source array, it gives a different result:
$arr = [
'27a' => 'foo',
'27' => 'foo',
'27b' => 'foo',
'27c' => 'foo',
];
ksort($arr);
print_r($arr);
// this prints
Array
(
[27b] => foo
[27c] => foo
[27] => foo
[27a] => foo
)
Does anyone know the logic behind this? Is this a bug or am I missing something?
EDIT: Thank you all for being interested in and answering my question. Although it's marked as duplicate, the other question didn't mention the weirder part: Why changing the order of the source array changes the result? It should give the same result with the same input set. Shall we discuss this too?
The reason that is happening is because it sees keys like '27a' as a string, and keys like '27' as an integer, even though it is quoted. You'll see the same results if you remove the quotes from the 27 key.
And, as the ksort page says: "Warning: Be careful when sorting arrays with mixed types values because sort() can produce unpredictable results."
Weird behavior for sure- unfortunately the best way to produce expected results when you have keys that look like integers (even if they are strings), is to specify the sort flag like SORT_STRING to ensure that you get the expected results every time.