I’ve stumbled upon something which confuses me. Before I though that if you save an array and it’s keys in integers, the array will automaticly sort itself.
That is, if I add the key 2, before the key 1, I’d though that the array would be sorted by the lowest number:
Array
(
[1] => one
[2] => two
)
Instead it comes up like this:
Array
(
[2] => two
[1] => one
)
Operation:
$arr = array();
$arr[2] = 'two';
$arr[1] = 'one';
This might seem like nothing, but sometimes I use foreach() or store ids in arrays and count on them to be sortered for maybe a INSERT-query, and then they need to be in correct order (due to AUTO INCREMENT).
So the question:
What is the expected ordering result in php?
I have a rather strong memory that I’ve sorted out arrays previously through output #1. Does this differ from php-version to php-version?
Thanks for answers!
A PHP array is actually an ordered map. It keeps the order, earlier elements will precede later ones.
You can use ksort to sort the array by key.