PHP array creation on first assignment

February 26, 2011 by alex

<?php
$test['key'] = 'value';
echo $test['key'];
?>

I thought I had an error here, since the code is making an assignment to an array which hasn’t yet been initialized. There was nothing in my error log, so I assumed that I hadn’t set my error_reporting value high enough. But even after using E_ALL | E_STRICT , the highest level possible, there’s still not so much as a peep.

As I’ve discovered, this is a perfectly legitimate way to initialize an array.

An existing array can be modified by explicitly setting values in it. This is done by assigning values to the array, specifying the key in brackets. The key can also be omitted, resulting in an empty pair of brackets ([]). If $arr doesn’t exist yet, it will be created, so this is also an alternative way to create an array. http://us2.php.net/manual/en/language.types.array.php

Well, heck, that’s convenient.

☙ ☙ ☙