Create non-existing array by accessing it in PHP?
411
I know that it is possible to add/modify array elements like this:
$a = ['zero', 'one', 'two']; //first create array
$a[4] = 'four';
$a[] = 'three';
Here I created the array before modifying it using[]
. But what happens if I do not create the variable with the array first? Will a new array be created and assigned to the variable automatically?
$b[2] = 'two'; // will create array?
$c[] = 'zero'; // will create array?
echo $d[1]; // will create array?
Answer
Solution:
$b[2] = 'two';
will create an array.$c[] = 'zero';
will create an array.echo $d[1];
will throw an undefined variable $d warning, or undefined offset 1 warning if $d exists but $d[1] does not.Answer
Solution:
Don't do that.
It's true that
$array[1] = 'foo';
will create an array but not always. If you already have a variable$array
then you won't get new array.Answer
Solution:
The short answer to your question is: Yes, if you access it for writing, PHP will create an array but not always!
To be more specific:
{-code-1}
- will create an array and will store the string{-code-2}
at key2
;$c[] = 'zero';
- will create an array and will store the stringzero
at key0
;echo $d[1]
- will NOT create an array; and it will NOT create$d[1]
if$d
already is an array but it doesn't have the key1
.You can check all these for yourself using
or
.
The complete answer is: DON'T do that! Always initialize the variables before using them!
Let me show you what happens when you ignore this advice and rely on PHP doing the initialization for you:
This code will produce the expected result:
Now, let's say several hundreds lines of code above in the same function the code looks like this:
Oops,
array_merge()
failed with the messagePHP Warning: array_merge(): Argument #1 is not an array
.What happened?
You expects that PHP will construct an array for you because you have used
$a
like$a[1] = 'b';
But PHP doesn't work this way!
It cannot guess what are you thinking. Variable
$a
already existed (it was created on top of the function and nobody unset it) and was holding a string. Because the notation$a[1] = 'b';
is a valid way to change a single character of a string, PHP just did that, completely unaware that you wish it to create an array.Conclusion?
Always, but always initialize your variables just before you use them. Never expect that PHP or some fairies will do that for you. Maybe they do it now but they may change their mind tomorrow and suddenly your code will stop working or it will start producing bad results.