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?
Generally, all variables should be explicitly initialized in their declaration. The descriptive comment is optional. In most cases, variable names are descriptive enough to indicate the use of the variable.
As PHP is a loosely typed language, so we do not need to declare the data types of the variables. It automatically analyzes the values and makes conversions to its correct datatype. After declaring a variable, it can be reused throughout the code. Assignment Operator (=) is used to assign the value to a variable.
Initializing a variable means specifying an initial value to assign to it (i.e., before it is used at all). Notice that a variable that is not initialized does not have a defined value, hence it cannot be used until it is assigned such a value.
A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ) Variable names are case-sensitive ( $age and $AGE are two different variables)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With