A variable is declared in PHP by putting a $ sign before the variable name. Here are some key facts to remember regarding variables:
We don't need to define the data types of the variables because PHP is a weakly typed language. It examines the values and converts them to the right data type automatically.
A variable can be reused throughout the code after it has been declared.
To assign a value to a variable, use the assignment operator (=).
The following is the syntax for declaring a variable in PHP:
$variablename=value; PHP variable declaration rules:
- A variable must begin with a dollar sign ($) and end with the variable name.
- Only alpha-numeric and underscore characters (A-z, 0-9, _) are allowed.
- The name of a variable must begin with a letter or the underscore (_) character.
- There can't be any spaces in the name of a PHP variable.
- It's important to remember that the variable name cannot begin with a number or a special symbol.
- Because PHP variables are case-sensitive, $name and $NAME are processed separately.
PHP Variable: Declaring string, integer, and float
Let's see the example to store string, integer, and float values in PHP variables.
echo "integer is: $x
echo "float is: $y
string is: knowledge 2life string
integer is: 100
float is: 40.6
PHP Variable: Sum of two variables
PHP Variable: case sensitive
Variable names in PHP are case-sensitive. As a result, the variable name "colour" differs from Color, COLOR, COLor, etc.
echo "My house is " . $COLOR . "
echo "My boat is " . $coLOR . "
My car is blue
Notice: Undefined variable: COLOR in C:\wamp\www\variable.php on line 4
My house is
Notice: Undefined variable: coLOR in C:\wamp\www\variable.php on line 5
My boat is
PHP Variable: Rules
PHP variables can only begin with a letter or an underscore.
Numbers and special symbols cannot be used to begin a PHP variable..
Parse error: syntax error, unexpected '4' (T_LNUMBER),
expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2