Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 236
Omer Avatar asked Jun 20 '15 15:06

Omer


People also ask

Is it necessary to initialize a variable?

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.

Why do we need to declare a variable in PHP?

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.

Can a variable be used without initialization?

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.

What are the rules to declare variable in PHP?

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)


1 Answers

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.

like image 114
Alexander Avatar answered Sep 16 '22 16:09

Alexander