Variables are used to store data which are further used and manipulated as per requirement or instructions. In PHP, a variable name is declared with a ‘$’ symbol and is followed by the variable name. It can be assigned a value using Assignment Operator (=). Syntax of declaring and defining PHP variable is:
<?php $variableName = value; ?>
However, there are some rules to follow while declaring a variable name in PHP which are mentioned below:
- As discussed earlier, a variable name must start with a ‘$’ symbol, followed by the name of its variable.
- Variable names are case sensitive. i.e.- $var is different from $VAR;
- A variable name must start with a letter or an underscore (_) followed by letters, numbers or underscores.
- A variable name cannot contain whitespace.
VARIABLE DECLARATION IN PHP
<?php $name = "Sehaj Kaur"; // String variable $age = 12; // Integer variable $english_marks = 99.5; // float variable $science_marks = 90.2; $total = $english_marks + $science_marks; // performing arithmetic operation echo "Name -> ".$name; // displaying values on screen echo "<br>Age -> ".$age; echo "<br>Total Marks -> ".$total; ?>
Name -> Sehaj Kaur
Age -> 12
Total Marks -> 189.7
Assign By Reference :
In PHP, we can also assign values to the variables by reference. The newly created variable becomes an alias for the original variable. If we change the value of a new variable it will affect the value of the original variable as well and vice-versa. The syntax looks like:
<?php $originalVar = “Programming”; // source variable $alias = &$originalVar; // value assigned by reference $alias = “Computer Programming”; // Altering the value of alias variable echo $originalVar; echo “<br>”.$alias; ?>
Note* : In PHP, if variables are not initialized they are supposed to have default values of the context in which they are used. For example : Integers and floats are set to zero by default, arrays and strings are empty if not initialized and a boolean is set to false.