Is it necessary to declare PHP array before adding values with []?
Just wanted to point out that the PHP documentation on arrays
actually talks about this in documentation.
From the PHP site, with accompanying code snippet:
$arr[key] = value;
$arr[] = value;
// key may be an integer or string
// value may be any value of any type
"If
$arr
doesn't exist yet, it will be created, so this is also an alternative way to create an array."
But, as the other answers stated...you really should declare a value for your variables because all kind of bad things can happen if you don't.
Think of the coders who come after you! If you just see $arr[] = 5
, you have no idea what $arr
might be without reading all the preceding code in the scope. The explicit $arr = array()
line makes it clear.
If you don't declare a new array, and the data that creates / updates the array fails for any reason, then any future code that tries to use the array will E_FATAL
because the array doesn't exist.
For example, foreach()
will throw an error if the array was not declared and no values were added to it. However, no errors will occur if the array is simply empty, as would be the case had you declared it.
Php is a loosely typed language. It's perfectly acceptable. That being said, real programmers always declare their vars.