Variables are used to store information and retrieve them when needed. They can be labeled with a meaningful name to be understood easily by the readers and ourselves.
The data stored in variables can be changed.
What can we do with variables?
We can think a variable as a box.
- A variable can have a name
- A variable can hold a value
- A variable's value can be updated
See the following image.
PHP Variable Naming
As a box can be labeled with a name, similarly, a variable can be (actually, should be) labeled with a name. In PHP, there are certain rules to follow when naming a variable.
Rules for PHP Variables
- The $ identifier should be added in front of the name of the variable.
- A variable name must start with a letter or underscore.
- A variable name cannot start with a number.
- A variable name cannot be $this. ($this is a special variable which cannot be assigned)
- A variable name can contain letters, numbers, and characters between 127-255 ASCII after the first character.
- Variable names are case sensitive.
<?php $name = 'Hyvor'; // valid $_name = 'Hyvor'; // valid - starts with an underscore $näme = 'Hyvor'; // valid - 'ä' is (Extended) ASCII 228 $1name = 'Hyvor'; // invalid - cannot start with a number $this = 'Hyvor'; // invalid - cannot assign value to $this
Tip: Always use a meaningful name for a variable.
PHP Declaring Variables
In programming, creating a variable is called declaring. But, in PHP, unlike other programming languages, there is no keyword to declare a variable.
Note: Strings should be wrapped with " (double-quotes) or ' (single-quotes). (We will learn more about quoting in PHP Output tutorial.)
When declaring a variable,
- The variable name must be on the left.
- The = sign as the assignment operator.
- Next, the value to be assigned.
- Finally, ; sign to say the statement is finished.
PHP Declaring Variables Example
<?php $month = "May"; $day = 22;
After running this part of the script,
- The text value, May is stored in the $month variable. (Note that " - double-quotes are not saved)
- The numeric value, 22 is stored in the $day variable.
PHP Reassigning Values to Variables
The output of the below code is "World" because it is the value of the last assignment of $text.
PHP Reassigning Variables Example
Run Example ››
<?php $text = 'Hello'; $text = 'World'; echo $text;