DEV Community

Michael
Michael

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

Top comments (0)

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay