A variable is a container for data which can change. In PHP all variables begin with a $ sign then a letter.
To assign a variable use the equals (=) operator:
$name="Fred";
Now $name contains the string of four letters.
For those who know other programming and scripting languages don't worry - PHP does not require you to declare variables. If that doesn't mean anything to you don't worry as that is one less thing to unlearn!
Numbers in variables
PHP is also pretty relaxed about what you put in it's variables. If you want to put a number into a variable just miss off the quotes:
$quantity=5;
Once you have something in a variable you can use it. The simplest example is to ECHO it to the Web page:
echo $quantity;
Try that.
Variables and double quotes
By using double quotes you can also use the variable within text being ECHOed:
echo "<p>Hello $name</p>";
The clever thing about PHP double quotes is that you can use variables inside strings of text and the variable value will just be inserted in the string when that is seen by the browser. So the browser will just see:
<p>Hello Fred</p>
Try that and remember to view the source code for the page in the browser.
Problems with variables inside double-quoted strings
Sometimes the PHP parser will get confused as it looks at a string and fails to spot a variable embedded in it. This is normally because there is not a space before and after the variable:
$stuff=" some text in a variable ";
echo "This is a string which contains $stuffwith the spaces in the variable rather than around it.";
PHP will think that the variable is called $stuffwith and, as $stuffwith is empty, will ECHO nothing. You fix this by using braces (curly brackets) around the variable to separate it from the string:
$stuff=" some text in a variable ";
echo "This is a string which contains {$stuff}with the spaces in the variable rather than around it.";
That should ECHO correctly - try both versions and see the results.
Variables and single quotes
As you found out on the last page you can use single quotes single quotes. If you do the text is not processed (parsed) in any way. So you cannot include variables inside single quotes. If you do include them then the variable name will just be echoed as a string. Try it by changing the quotes in an ECHO line which includes a variable.
If you want variables to appear on the Web page as values when you are using single quotes you need to:
- close the quoted string
- add on the variable
- start the string again
This is called concatentation and looks like this:
echo '<p>Hello '.$name.', how are you?</p>';
Concatentation can get very confusing at first which is why these tutorials tend to use double quotes at first. However, single quotes are quicker and also allow you to echo lots of HTML easily so you may end up using them more in the end. Try some ECHO statements with single quotes an concatenation.



