PHP Tutorial 2
By James Moran
Using Variables
Following on from tutorial one, we will now create a variable which will contain the text Hello World.
1. As before, create your file but call it program2.php
2. Again, add the arrow question marks
3. Between them this time, type
$textvariable = 'Hello Word';
A PHP variable can contain any information and unlike many other programming languages, the variable doesn't have to be predefined as a certain type (like string, integer, real, etc).
The variable always has to start with a dollar symbol ($) but can be named anything you like as long as the characters you use are alphanumeric and are joined text (no spaces). You can separate words with _ (underscore) if you want.
The equals symbol in this case tells the browser that this variable contains this data.
The single quotes show that text is between them and we have the usual semi-colon denoting the end of the code line.
4. Now we are going to echo again so under the previous line type
echo $textvariable;
Note that this time you don't need the single quotes, this is because you are not echoing text, you are echoing a variable containing text.
The whole program should read
<?
$textvariable = 'Hello Word';
echo $textvariable;
?>
Save, upload and view your file. You should have exactly what you had in the first tutorial (white page with just Hello Word written in black)
5. Now lets make this a little more interesting. We are now going to echo text and a couple of variables.
Save your file again but now under the name of program3.php. Delete the words 'Hello World' and replace this with the word 'fox'. This should now read
$textvariable = 'fox';
Now create another variable called textvariable2 and with the value of 'dog'. This will look like
$textvariable2 = 'dog';
Now to join text to a variable, two variables or even separate pieces of text, you use a . (full stop). This can be while echoing or when creating a new variable. Write your echo as follows.
echo 'The quick brown '.$textvariable.' fox jumps over the lazy ' .$textvariable2;
The whole program should read as follows
<?
$textvariable = 'fox';
$textvariable2 = 'dog';
echo 'The quick brown '.$textvariable.' fox jumps over the lazy '.$textvariable2;
?>
Save, upload and view your file. This should read
The quick brown fox jumps over the lazy dog
That's it for tutorial 2, have another cookie.