PHP Variables
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.
File: variable1.php
";
echo "integer is: $x
";
echo "float is: $y
";
?>
Output:
string is: knowledge 2life string
integer is: 100
float is: 40.6
PHP Variable: Sum of two variables
File: variable2.php
Output:
14
PHP Variable: case sensitive
Variable names in PHP are case-sensitive. As a result, the variable name "colour" differs from Color, COLOR, COLor, etc.
File: variable3.php
";
echo "My house is " . $COLOR . "
";
echo "My boat is " . $coLOR . "
";
?>
Output:
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..
File: variablevalid.php
$_b";
?>
Output:
knowledge 2life
knowledge 2life
File: variableinvalid.php
$*d";
?>
Output:
Parse error: syntax error, unexpected '4' (T_LNUMBER),
expecting variable (T_VARIABLE)
or '$' in C:\wamp\www\variableinvalid.php on line 2