Variables are “container” used for storing information.
- In PHP, a variable is declared using a $ sign
- The assignment operator (=) used to assign value to a variable
- To get the data type of a variable, use the var_dump() function.
PHP Variables Example:
<?php
$variable_name=value;
?>
Note: As PHP is a loosely typed language, so we do not need to declare the data types of the variables.
It is automatically find the correct datatype.
PHP Variable Naming Conventions
There are a few rules that you need to follow when choosing a name for your PHP variables.
- Variable names cannot contain spaces.
- Variables names can contain letters (a-z and A-Z), numbers (0-9) and underscores (_).
- Variable names can begin with letters or an underscore, but cannot begin with numbers.
- PHP automatically converts the variable to the correct data type, depending on its value.
- The assignment operator (=) used to assign value to a variable.
- Variable names are case-sensitive ($age and $AGE are two different variables)
<?php
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
?>
Get the Type:
To get the data type of a variable, use the var_dump() function.
<!DOCTYPE html>
<html>
<body>
<?php
$x = 10;
var_dump($x);
?>
</body>
</html>
Output:
int(10)