Is it necessary to Initialize / Declare variable in PHP?

Omer picture Omer · Jun 20, 2015 · Viewed 40.1k times · Source

This question's purpose is to only gain knowledge or information for me and many like me.

So my question is:

Is it necessary to Initialize / Declare a variable before a loop or a function?

Asking this question is for my confusion because whether I initialize / declare variable before or not my code still works.

I'm sharing a 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 piece of code works same for me, so is necessary to Initialize / Declare a variable at the beginning?

Answer

Alexander picture Alexander · Jun 20, 2015

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.