In all programming languages there is some way to create a variable. All a variable is, is a memory location with a label like “name”. Therefore we can store a name like “Tom” in memory for use later. Later on, we could ever change this variable “name”, from “Tom” to “Sam” if we needed to by using this variable.
In PHP to create a variable you simply place a ‘$’ symbol before the variable name. Therefore to create a variable called “name” we would write:
<?php
$name = "Tom";
?>
Variable name can not have space, but has to be a continues string of character using ‘a’-‘z’, ‘A’-‘Z’, ‘0’-‘9’ or the ‘-‘ character.
Examples:
Value variable names
Name, address, numberOfPages, size_of_page, Line1, Line_2, Line_99, the_6th_line
Invalided variable names
Number of pages, line#1, CostIn£
In the example above we create a variable called “name” and the set is to the value “Tom”. This is done using the special symbol ‘=’. This symbol is called the assignment operator, and we will use this operator a lot.
Finally, at the end of the line there is another special character, this is a semicolon ‘;’. The semicolon is used to tell the computer that this is the end of this command. The server then interprets and runs this command.
We can now create a variable for a name and send it to the client.
<?php
$name = "Tom";
echo "My name is $name";
?>
Variable in PHP cannot just hold strings of characters, but integers, doubles and Boolean values, e.g.
<?php
$name = "Tom";
$age = 21;
$height = 1.65;
$single = true;
echo "My name is $name";
echo "I am $age year old";
echo "and $height m tall";
echo "if you asked me if I was single I would say $single";
?>
When you run this script you will see that name, age and height are echoed as you might expect, but a Boolean value is either a ‘0’ or ‘1’.
Also note we did not have to tell the script what type each variable is. The act of assigning it value will determine what type it is.
This means that if you change is value type then the variable type will change also, e.g.
<?php
$name = "Tom";
echo "My name is $name";
Sname = 21;
echo "I am $name year old";
?>
In this example the variable “name” was initially a string holding the value “Tom”, but then in line 4 the variable “name” has become an integer. This was due to assigning the value 21 to the variable.