Variable is a place to store value, such as a text string «Hello World!»(string) 4 (integer). Variable can be used anywhere in your code, instead of having to enter the actual values over and over again. In PHP you define a variable as follows:
$ variable_name = Value;
As you can see, any variable starts with a dollar sign. You need to remember that otherwise it will not work. This is a common mistake made by novice PHP programmers!
Note: In addition, variable names are case sensitive, so use the same spelling when using a variable.
Variables $a_number and $A_number different variables in the eyes of PHP.
A simple example with variables
To use variables in php we must first declare it (think of a name for it) and set the value to it. Here’s how to do it correctly:
$hello = "Hello World!";
$a_number = 4;
$anotherNumber = 8;
Note: PHP does not require variable declarations before use.
Allowed variable names
There are several rules that must be followed when choosing a name for your PHP variables.
- PHP variables must start with a letter or an underscore “_”
- PHP variables can contain only alphanumeric characters and underscores. a-z, A-Z, 0-9, or _
- Variables of more than one word can be separated by underlining. $ my_variable
- Variables from more than one word can also be divided in case. $ myVariable