Learn How To Define Variable In PHP With Example
Variable In PHP play an important role in every programing language. Variables are used to store data, like string of text, numbers, etc. Variable values can change over the course of a script.
All variable in PHP start with a $ sign, followed by the name of the variable. A variable name must start with a letter or the underscore character. A variable name cannot start with a number. A variable name in PHP can only contain alphanumeric characters and underscores ( A-z , 0-9 , and _ ).
Here’re some important things to know about variables:
- In PHP, a variable does not need to be declared before adding a value to it. PHP automatically converts the variable to the correct data type, depending on its value.
- After declaring a variable it can be reused throughout the code.
- The assignment operator (=) used to assign value to a variable.
- All variables in PHP are denoted with a leading dollar sign ($).
- The value of a variable is the value of its most recent assignment.
- Variables can, but do not need, to be declared before assignment.
- Variables used before they are assigned have default values.
- A variable name cannot start with a number.
- A variable name cannot contain spaces.
- PHP does a good job of automatically converting types from one to another when necessary.
Note:Variable name in PHP are case sensitive, it means $A and $a are two different variables. So that, be careful while defining variable names.
In PHP variable can be declared as: $var_name = value;
Variable In PHP With Example
// Declaring variables
$Viewer = "Hello Viewer!";
$Views = 100;
// Displaying variables value
echo $ Viewer; // Output: Hello Viewer!
echo $ Views; // Output: 100
In the above example we have created two variables where first one has assigned with a string value and the second has assigned with a number. We’re displayed the variables values in the browser using the echo statement.