DEV Community


Posted on

Array initialisation and key data types in PHP

When initialising PHP array elements the order of the keys can result in changes to all the key types, even when you explicitly specify the key value/type.

$foo[0] = 'a';
$foo[1] = 'b';
$foo[2] = 'c';
$foo[3] = 'd';

// $foo has integer keys

$bar[0] = 'a';
$bar[1] = 'b';

// $bar has integer keys

$bar[3] = 'c';

// $bar now has string keys, because we skipped element 2
// this is despite us using an integer key

$bar[2] = 'd';

// $bar still has string keys, despite it having element 2
// and it being declared with an integer key

json_encode($foo) !== json_encode($bar);

// True
Enter fullscreen mode Exit fullscreen mode

Discussion (0)