PHP Beginners Tutorial Lesson 2 - Basic Variables
Open up the file you created in Lesson 1 and delete all of the contents except for the opening and closing PHP bits.
File now looks like
<?php
?>
First we are going to set a variable. A variable is a name given to a piece of memory that we store information in while the script is running.
To create a variable we use the dollar sign, followed by the name of the variable
<?php
$thevariable=’HELLO’;
?>
That script has just created a variable called ‘thevariable’ and it has stored ‘HELLO’ in it.
to output the contents of a variable we again use an echo statement.
<?php
$thevariable=’HELLO’;
echo $thevariable;
?>
This will output onto the HTML page ‘HELLO’; Notice we don’t need to put the variable in inverted commas when we are echoing. We only need to do that if it is a piece of text.
If we want to assign a number to a variable we do something similar
<?php
$thevariable=1;
echo $thevariable;
?>
will output ‘1’;
If we want to add two numbers together we can do..
<?php
$variable1=1;
$variable2=2;
$result=$variable1+$variable2;
echo $result;
?>
This will output ‘3’;
Have a play and see what happens with those results. Use PHP as if it were a calculator to get some more interesting results.
Next lesson we will be looking at the IF statement and the WHILE Loop.