phparrays

Is it necessary to declare PHP array before adding values with []?


$arr = array(); // is this line needed?
$arr[] = 5;

I know it works without the first line, but it's often included in practice.

What is the reason? Is it unsafe without it?

I know you can also do this:

$arr = array(5);

but I'm talking about cases where you need to add items one by one.


Solution

  • It's recommended to always initialize arrays before use. Right from the PHP manual:

    If $arr doesn't exist yet or is set to null or false, it will be created, so this is also an alternative way to create an array. This practice is however discouraged because if $arr already contains some value (e.g. string from request variable) then this value will stay in the place ... It is always better to initialize a variable by a direct assignment.

    Also, if adding new values is conditional, and no values gets actually added, it will lead to infamous Undefined variable Warning level error.

    For example, foreach() will throw such 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.