PHP Array Order – Another reason why php sucks
I can’t come up with words to describe this:
#!/usr/bin/php
$array1 = Array( 'a', 'b', 'c');
$array2[2] = 'c';
$array2[1] = 'b';
$array2[0] = 'a';
var_dump($array1);
var_dump($array2);
results in:
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
array(3) {
[2]=>
string(1) "c"
[1]=>
string(1) "b"
[0]=>
string(1) "a"
}
My expectation is that the second array should be identical to the first. It should ignore the order I put the elements in, because I’m adding them by index.
Of course, there is a solution to my problem! In typical PHP fashion, there is ksort.
#!/usr/bin/php
$array1 = Array( 'a', 'b', 'c');
$array2[2] = 'c';
$array2[1] = 'b';
$array2[0] = 'a';
var_dump($array1);
var_dump($array2);
ksort($array2);
var_dump($array2);
Gives me what I’m looking for:
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
array(3) {
[2]=>
string(1) "c"
[1]=>
string(1) "b"
[0]=>
string(1) "a"
}
array(3) {
[0]=>
string(1) "a"
[1]=>
string(1) "b"
[2]=>
string(1) "c"
}
I guess that’s the problem when you don’t have separate primitives for hash tables.


I’d say this has more to do with var_dump() than PHP being brain damaged. Not that there isn’t enough brain damage in PHP to argue for that, however.
May 24th, 2008 at 9:02 amActually, if you iterate through the array, it comes out in the c, b, a order. You’d get the same behavior using foreach(), but not for(;;).
May 24th, 2008 at 9:10 am