The Cult of Gary

23 May

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.

2 Responses to “PHP Array Order – Another reason why php sucks”

  1. 1
    Matt Simmons Says:

    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.

  2. 2
    gary.richardson Says:

    Actually, 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(;;).

Leave a Reply

© 2010 The Cult of Gary | Entries (RSS) and Comments (RSS)

GPSwordpress logo