Skip to content
Advertisement

Is it necessary to Initialize / Declare variable in PHP?

Is it necessary to initialize / declare a variable before a loop or a function?

Whether I initialize / declare variable before or not my code still works.

I’m sharing demo code for what I actually mean:

$cars = null;

foreach ($build as $brand) {
     $cars .= $brand . ",";
}

echo $cars;

Or

foreach ($build as $brand) {
     $cars .= $brand . ",";
}

echo $cars;

Both pieces of code works same for me, so is it necessary to initialize / declare a variable at the beginning?

Advertisement

Answer

PHP does not require it, but it is a good practice to always initialize your variables.

If you don’t initialize your variables with a default value, the PHP engine will do a type cast depending on how you are using the variable. This sometimes will lead to unexpected behaviour.

So in short, in my opinion, always set a default value for your variables.

P.S. In your case the value should be set to “” (empty string), instead of null, since you are using it to concatenate other strings.

Edit

As others (@n-dru) have noted, if you don’t set a default value a notice will be generated.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement