A variable is a named memory location which is used to store programs input data and its computational results during execution.The value of variable may change during the execution.
Variables are created in RAM , which is temporary memory that’s why the stored data in variables is also temporary. The data stored in the variable is automatically removed when a program ends.
*A quantity whose value can be changed during
program execution is called Variable.*
In php ,Like all other languages variables are used to store values or data.PHP is a very loosely typed language. This means that variables do not have to be declared before they are used, and that PHP always converts variables to the type required by their context when they are accessed.
Rules for PHP variable names
- The name of the variable is given by the user at the design time.
- A variable starts with the $ sign.
- A variable name may include letters , numbers and underscores(_).
- The first character of variable must be a letter. The variables 7minute, #home, and 2kg are invalid.
- Variable names are case-sensitive ($marks and $MARKS are two different
- Variables are assigned with the = operator, the variable on the left-hand side and the expression to be evaluated on the right.
The most simple example about variables in PHP:
<h1> PHP Variable </h1>
$var = “country”;
echo “I love my $var! “;
I love my country!
There is another example to declare variables and display the sum of them.
<h1> PHP Variables Sum </h1>
$first = 7;
$second = 21;
echo $first + $second;
PHP Variables Scope
Variable scope is known as its boundary within it can be visible or accessed by code.
Depending on the scopes, PHP has three variable scopes:
i) Local Variables
ii) Global Variables
Variables that are created within the function,and can only be accessed by that function. They are generally temporary variables that are used to store partially processed results prior to the function’s return.