All variables start with the dollar sign $. Variables will automatically become the type required so there’s no need to predefine them. For example:
<?php $variable = "Hello"; ?> or
<?php $variable = 5; ?> All strings have either double or single quotes around them. Personally I always use double quotes but this is a personal preference.
To print a variable you can use print but you do not require double quotes around the variable (however it will work with either method). The following are allowed:
// set the variable
$variable = "Sarah";
//print a string with the variable in
print "Hello $variable, how are you";
// print a string with the variable 'concatenated'
print "Hello ".$variable.", how are you";
Here both statements will display the same. In the second concatenation has also been used (the full stop / period “.” ) – explained later.
Variables can of course have all arithmetic operations performed on them when in a number format, or string operations performed, when in string format. For example:
$a = 2;
$b = 6;
// multiple a by b and store the result in c
$c = $a * $b;
print $c; // answer is of course 12
Also another helpful option (will be important later on) is a variable of a variable. For example:
$a = "name";
$$a = 3;
print $a; // gives the number 2
print $name; // gives the number 3
This makes a variable of a variable. So at first $a is assigned to the string “name”, and the the variable of the variable a, which is currently name, is assigned to 3. This will come in handy later on.