In the previous section, you saw what a Associative array was, and that they use text as the Key. In this lesson, you'll learn how to access each element in Associative array - with the For Each loop. So study the following code (try it out in a script):
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
foreach ($full_name as $key_name => $key_value) {
print "Key = " . $key_name . " Value = " . $key_value . "
";
}
The For Each loop is a little more complex than other loops you've met. In the script above, we set up the array as normal. But the first line of the loop is this:
foreach ($full_name as $key_name => $key_value) {
Notice that the name of the loop is one word: foreach and NOT for each. Next comes the round brackets. Inside of the round brackets, we have this:
$full_name as $key_name => $key_value
You start by typing the name of the array you want to loop round. For us, that was $full_name. Next is this:
as $key_name => $key_value
This means, "Get the Key and its Value from the array called $full_name. The Key is called $key_name in the script above, and the value is called $key_value. But these are just variable names. You can call them almost anything you like. Would could have had this:
foreach ($full_name as $first_name => $surname) {
When you use foreach, PHP knows that it's accessing the key name first and then the key value. It knows this because of the => symbol between the two. It then returns the values into your variable names, whatever they may be.
Once your loop code is executed (a print statement for us), it then loops round and returns the next Key/Value pair, storing the results in your variables.
If you need to access values from an Associative array, then, use a foreach loop.
In the next few sections, you'll see some useful things you can do with arrays.
Monday, October 26, 2009
PHP Arrays - Using Text as Keys
Your arrays keys don't have to be numbers, as in the previous section. They can be text. This can help you remember what's in a key, or what it's supposed to do. When you use text for the keys, you're using an Associative array; when you use numbers for the keys, you're using a Scalar array. Here's an array that sets up first name and surname combinations:
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
Fans of a certain band will know exactly who these people are! But look at the keys and values now:
David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"
This is easier to remember than this:
0 => "Gilmour",
1 => "Mason",
2 => "Waters",
3 => "Wright"
To access the values in an Associative array, just refer to the Key name:
print $full_name["David"];
However, because Associative arrays don't have numbers for the keys, another technique is used to loop round them – the For Each loop. We'll see how they work in the next part.
$full_name = array( );
$full_name["David"] = "Gilmour";
$full_name["Nick"] = "Mason";
$full_name["Roger"] = "Waters";
$full_name["Richard"] = "Wright";
Fans of a certain band will know exactly who these people are! But look at the keys and values now:
David => "Gilmour",
Nick => "Mason",
Roger => "Waters",
Richard => "Wright"
This is easier to remember than this:
0 => "Gilmour",
1 => "Mason",
2 => "Waters",
3 => "Wright"
To access the values in an Associative array, just refer to the Key name:
print $full_name["David"];
However, because Associative arrays don't have numbers for the keys, another technique is used to loop round them – the For Each loop. We'll see how they work in the next part.
Getting at the Values Stored in PHP Arrays
OK, so you now know how to store values in your array. But how do you get at those values? Well, there are few ways you can do it. But the "Key" is the key. Here's an example for you to try:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
?>
The array is the same one we set up before. To get at what is inside of an array, just type the key number you want to access. In the above code, we're printing out what is held in the 0 position (Key) in the array. You just type the key number between the square brackets of your array name:
print $Array_Name[0];
You can also assign this value to another variable:
$key_data = $Array_Name[0];
print $key_data;
It's a lot easier using a loop, though. Suppose you wanted to print out all the values in your array. You could do it like this:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
print $seasons[1];
print $seasons[2];
print $seasons[3];
Or you could do it like this:
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
print $seasons[$key_Number];
}
If you have many array values to access, then using a loop like the one above will save you a lot of work!
You don't have to use numbers for the keys - you can use text. We'll see how to do that in the next part.
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
?>
The array is the same one we set up before. To get at what is inside of an array, just type the key number you want to access. In the above code, we're printing out what is held in the 0 position (Key) in the array. You just type the key number between the square brackets of your array name:
print $Array_Name[0];
You can also assign this value to another variable:
$key_data = $Array_Name[0];
print $key_data;
It's a lot easier using a loop, though. Suppose you wanted to print out all the values in your array. You could do it like this:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
print $seasons[0];
print $seasons[1];
print $seasons[2];
print $seasons[3];
Or you could do it like this:
for ($key_Number = 0; $key_Number < 4; $key_Number++) {
print $seasons[$key_Number];
}
If you have many array values to access, then using a loop like the one above will save you a lot of work!
You don't have to use numbers for the keys - you can use text. We'll see how to do that in the next part.
How to Set up an Array in PHP
In the code on the previous page, we had four items, and all with a different variable name: $Order_Number1, $Order_Number2, $Order_Number3, and $Order_Number4. With an array, you can just use a single name. You set up an array like this:
$Order_Number = array( );
First you type out what you want your array to be called ($Order_Number, in the array above) and, after an equals sign, you type this:
array( );
So setting up an array just involves typing the word array followed by a pair of round brackets. This is enough to tell PHP that you want to set up the array. But there's nothing in the array yet. All we're doing with our line of code is telling PHP to set up an array, and give it the name $Order_Number.
You can use two basic methods to put something into an array.
Method One – Type between the round brackets
The first method involves typing your values between the round brackets of array(). In the code below, we're setting up an array to hold the seasons of the year:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
So the name of the array is $seasons. Between the round brackets of array(), we have typed some values. Each value is separated by a comma:
("Autumn", "Winter", "Spring", "Summer")
Arrays work by having a position, and some data for that position. In the above array, "Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in position 3.
The first position is always zero, unless you tell PHP otherwise. But the position is know as a Key. The Key then has a value attached to it. You can specify your own numbers for the Keys. If so, you do it like this:
$seasons = array(1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer");
So you type a number for your key, followed by the equals sign and a right angle bracket ( => ). In the array above, the first Key is now 1 and not 0. The item stored under key 1 is "Autumn". The last key is 4, and the item stored under key 4 is "Summer". Careful of all the commas, when you set up an array like this. Miss one out and you'll get error messages. Here's the keys and values that are set up in the array above:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
If you let PHP set the keys for you, it would be this:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
You can have numbers for the values of your keys. Here's an array that stores the numbers 10, 20, 30 and 40.
$Array_Name = array(10, 20, 30, 40);
Because no keys were specified, PHP will set your array up like this:
0=> 10,
1=> 20,
2=> 30,
3=> 40
Here's the same array again, only this time we're specifying our own key:
$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
This array will then look like this:
1=> 10,
2=> 20,
3=> 30,
4=> 40
So the key name is typed before the => symbol, and the data stored under this key is to the right.
You can store text and numbers in the same array:
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer"
Method two – Assign values to an array
Another way to put values into an array is like this:
$seasons = array();
$seasons[]="Autumn";
$seasons[]="Winter";
$seasons[]="Spring";
$seasons[]="Summer";
Here, the array is first set up with $seasons = array();. This tells PHP that you want to create an array with the name of $seasons. To store values in the array you first type the name of the array, followed by a pair of square brackets:
$seasons[]
After the equals sign, you type out what you want to store in this position. Because no numbers were typed in between the square brackets, PHP will assign the number 0 as the first key:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
This is exactly the same as the array you saw earlier. If you want different numbers for your keys, then simply type them between the square brackets:
$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";
PHP will then see your array like this:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
This method of creating arrays can be very useful for assigning values to an array within a loop. Here's some code:
$start = 1;
$times = 2;
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
Don't worry if you don't fully understand the code above. The point is that the values in the array called $answer, and the array key numbers, are being assigned inside the loop. When you get some experience with arrays, you'll be creating them just like above!
In the next part, we'll take a look at how to get at the values stored in your arrays.
$Order_Number = array( );
First you type out what you want your array to be called ($Order_Number, in the array above) and, after an equals sign, you type this:
array( );
So setting up an array just involves typing the word array followed by a pair of round brackets. This is enough to tell PHP that you want to set up the array. But there's nothing in the array yet. All we're doing with our line of code is telling PHP to set up an array, and give it the name $Order_Number.
You can use two basic methods to put something into an array.
Method One – Type between the round brackets
The first method involves typing your values between the round brackets of array(). In the code below, we're setting up an array to hold the seasons of the year:
$seasons = array("Autumn", "Winter", "Spring", "Summer");
So the name of the array is $seasons. Between the round brackets of array(), we have typed some values. Each value is separated by a comma:
("Autumn", "Winter", "Spring", "Summer")
Arrays work by having a position, and some data for that position. In the above array, "Autumn" is in position zero, "Winter" is in position 1, "Spring" is in position 2, and "Summer" is in position 3.
The first position is always zero, unless you tell PHP otherwise. But the position is know as a Key. The Key then has a value attached to it. You can specify your own numbers for the Keys. If so, you do it like this:
$seasons = array(1 => "Autumn", 2 => "Winter", 3 => "Spring", 4 => "Summer");
So you type a number for your key, followed by the equals sign and a right angle bracket ( => ). In the array above, the first Key is now 1 and not 0. The item stored under key 1 is "Autumn". The last key is 4, and the item stored under key 4 is "Summer". Careful of all the commas, when you set up an array like this. Miss one out and you'll get error messages. Here's the keys and values that are set up in the array above:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
If you let PHP set the keys for you, it would be this:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
You can have numbers for the values of your keys. Here's an array that stores the numbers 10, 20, 30 and 40.
$Array_Name = array(10, 20, 30, 40);
Because no keys were specified, PHP will set your array up like this:
0=> 10,
1=> 20,
2=> 30,
3=> 40
Here's the same array again, only this time we're specifying our own key:
$Array_Name = array(1 => 10, 2 => 20, 3 => 30, 4 => 40);
This array will then look like this:
1=> 10,
2=> 20,
3=> 30,
4=> 40
So the key name is typed before the => symbol, and the data stored under this key is to the right.
You can store text and numbers in the same array:
$Array_Name = array(1 => 10, 2 => "Spring", 3 => 30, 4 => "Summer");
The above array would then look like this:
1=> 10,
2=> "Spring",
3=> 30,
4=> "Summer"
Method two – Assign values to an array
Another way to put values into an array is like this:
$seasons = array();
$seasons[]="Autumn";
$seasons[]="Winter";
$seasons[]="Spring";
$seasons[]="Summer";
Here, the array is first set up with $seasons = array();. This tells PHP that you want to create an array with the name of $seasons. To store values in the array you first type the name of the array, followed by a pair of square brackets:
$seasons[]
After the equals sign, you type out what you want to store in this position. Because no numbers were typed in between the square brackets, PHP will assign the number 0 as the first key:
0=> "Autumn",
1=> "Winter",
2=> "Spring",
3=> "Summer"
This is exactly the same as the array you saw earlier. If you want different numbers for your keys, then simply type them between the square brackets:
$seasons[1]="Autumn";
$seasons[2]="Winter";
$seasons[3]="Spring";
$seasons[4]="Summer";
PHP will then see your array like this:
1=> "Autumn",
2=> "Winter",
3=> "Spring",
4=> "Summer"
This method of creating arrays can be very useful for assigning values to an array within a loop. Here's some code:
$start = 1;
$times = 2;
$answer = array();
for ($start; $start < 11; $start++) {
$answer[$start] = $start * $times;
}
Don't worry if you don't fully understand the code above. The point is that the values in the array called $answer, and the array key numbers, are being assigned inside the loop. When you get some experience with arrays, you'll be creating them just like above!
In the next part, we'll take a look at how to get at the values stored in your arrays.
What is an Array? php
You know what a variable is – just a storage area where you hold numbers and text. The problem is, a variable will hold only one value. You can store a single number in a variable, or a single string. An array is like a special variable, which can hold more than one number, or more than one string, at a time. If you have a list of items (like a list of customer orders, for example), and you need to do something with them, then it would be quite cumbersome to do this:
$Order_Number1 = "Black shoes";
$Order_Number2 = "Tan shoes";
$Order_Number3 = "Red shoes";
$Order_Number4 = "Blue shoes";
What if you want to loop through your orders and find a specific one? And what if you had not four orders but four hundred? A single variable is clearly not the best programming tool to use here. But an array is! An array can hold all your orders under a single name. And you can access the orders by just referring to the array name.
If that's a bit confusing right now, let’s make a start on explaining how arrays work.
$Order_Number1 = "Black shoes";
$Order_Number2 = "Tan shoes";
$Order_Number3 = "Red shoes";
$Order_Number4 = "Blue shoes";
What if you want to loop through your orders and find a specific one? And what if you had not four orders but four hundred? A single variable is clearly not the best programming tool to use here. But an array is! An array can hold all your orders under a single name. And you can access the orders by just referring to the array name.
If that's a bit confusing right now, let’s make a start on explaining how arrays work.
How to break out of PHP Loops
There are times when you need to break out of a loop before the whole thing gets executed. Or, you want to break out of the loop because of an error your user made. In which case, you can use the break statement. Fortunately, this involves nothing more than typing the word break. Here’s some not very useful code that demonstrates the use of the break statement:
$TeacherInterrupts = true;
$counter = 1;
while ($counter < 11) {
print(" counter = " + $counter + "
");
if ($TeacherInterrupts = = true) break;
$counter++;
}
Try the code out and see what happens.
Ok, that's enough of loops. For now. In the next section, we'll take a look at what arrays are, and how useful they can be. (Yes, there'll be loops!)
$TeacherInterrupts = true;
$counter = 1;
while ($counter < 11) {
print(" counter = " + $counter + "
");
if ($TeacherInterrupts = = true) break;
$counter++;
}
Try the code out and see what happens.
Ok, that's enough of loops. For now. In the next section, we'll take a look at what arrays are, and how useful they can be. (Yes, there'll be loops!)
Do While loops in PHP
This type is loop is almost identical to the while loop, except that the condition comes at the end:
do
statement
while (condition)
The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed.
Don’t worry too much about do … while loops. Concentrate on For loops and While loops. But there is another type of loop that comes in handy - the For Each loop. First, a quick word about the break statement.
do
statement
while (condition)
The difference is that your statement gets executed at least once. In a normal while loop, the condition could be met before your statement gets executed.
Don’t worry too much about do … while loops. Concentrate on For loops and While loops. But there is another type of loop that comes in handy - the For Each loop. First, a quick word about the break statement.
While Loops in PHP
Instead of using a for loop, you have the option to use a while loop. The structure of a while loop is more simple than a for loop, because you’re only evaluating the one condition. The loop goes round and round while the condition is true. When the condition is false, the programme breaks out of the while loop. Here’s the syntax for a while loop:
while (condition) {
statement
}
And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
");
$counter++;
}
The condition to test for is $counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When $counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.
If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the $counter variable is incremented. Like this:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
");
//$counter++;
}
Notice the two forward slashes before $counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – $counter will always be 1.
Here’s a while loop that prints out the 2 times table. Try it out in a script.
$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "
");
$start++;
}
The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on? Make sure you understand the code. If not, it’s a good idea to go back and read this section again. You won’t be considered a failure. Honest!
In the next part, we'll have a brief look at Do ... While loops
while (condition) {
statement
}
And here’s some code to try. All it does is increment a variable called counter:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
");
$counter++;
}
The condition to test for is $counter < 11. Each time round the while loop, that condition is checked. If counter is less than eleven then the condition is true. When $counter is greater than eleven then the condition is false. A while loop will stop going round and round when a condition is false.
If you use a while loop, be careful that you don’t create an infinite loop. You’d create one of these if you didn’t provide a way for you condition to be evaluated as true. We can create an infinite loop with the while loop above. All we have to do is comment out the line where the $counter variable is incremented. Like this:
$counter = 1;
while ($counter < 11) {
print (" counter = " . $counter . "
");
//$counter++;
}
Notice the two forward slashes before $counter++. This line will now be ignored. Because the loop is going round and round while counter is less than 11, the loop will never end – $counter will always be 1.
Here’s a while loop that prints out the 2 times table. Try it out in a script.
$start = 1;
$times = 2;
$answer = 0;
while ($start < 11) {
$answer = $start * $times;
print ($start . " times " . $times . " = " . $answer . "
");
$start++;
}
The while loop calculates the 2 times tables, up to a ten times 2. Can you see what’s going on? Make sure you understand the code. If not, it’s a good idea to go back and read this section again. You won’t be considered a failure. Honest!
In the next part, we'll have a brief look at Do ... While loops
The Code for the PHP Times Table Programme
The code for the Times Table in the previous page uses a For Loop. The Start for the loop will come from the Start Number textbox, and the end of the loop will come from the End Number textbox. Here's the code in full (without the HTML):
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
for($start; $start <= $end; $start++) {
$answer = $start * $times;
print $start . " multiplied by " . $times . " = " . $answer . "
";
}
}
?>
Code Explanation
We need all those numbers from the textboxes on the form, so we start with:
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
}
The first line just puts a value in the variable called $times . This is so that the "Multiply By" textbox will have a default value when the page is loaded.
Next we use the isset( ) function again, just to check if the user clicked the Submit button. This is exactly the same as you saw in the last section.
To get the values from the textboxes, we use the following:
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Again, this is code you met in the last section. You just assign the values from the textboxes to the new variables using $_POST[]. In between the square brackets, we've typed the NAME of the HTML textboxes. So this gives us the values that the user entered on the form. Next comes out For Loop:
for($start; $start <= $end; $start++) {
$answer = $start * $times;
}
Let's look at that first line again:
for($start; $start <= $end; $start++) {
So we have a starting value for our loop, an end value, and an update expression. The starting value is coming from the variable called $start. This will be whatever number the user entered in the first textbox. The default is 1. Look at the end value, though:
$start <= $end
The end value is when the value in the variable called $start is less than or equal to the value held in the variable called $end. This works because we're increasing the value of $start each time round the loop. The variable called $end is a fixed value, and comes from the textbox on the form.
The last part of the loop code is the update expression. This tells PHP to increase the value of $start each time round the loop:
$start++
The double plus symbol (++) means "add 1 to the number held in $start".
And that's the essence of for loops: provide a start value, an end value, and how you want to update each time round the loop.
The code inside the for loop, however, the code that gets executed each time round the loop, is this:
$answer = $start * $times;
Remember, the variable $times holds the times table, the 2 times table by default. This is being multiplied by whatever is inside the variable $start. Each time round the loop, $start will have a different value – first 1, then 2, then 3, etc. The answer is then stored in the variable that we called $answer. So it's really doing this:
$answer = 1 * 2;
$answer = 2 * 2;
$answer = 3 * 2;
etc
Finally, we displayed the result to the page like this:
print $start . " multiplied by " . $times . " = " . $answer . "
";
This is just concatenation. See if you can work out what all the parts do!
And that’s it – your very own times table generator. If you have children, show them the programme you wrote. They’ll be very impressed and tell you how brilliant you are. Children are like that.
Of course, your programme is not perfect, which I’m sure the children will discover. Especially if they enter a 10 as the start number and a 1 as the end number. Why doesn't it print anything out? Anything you can do to trap this error? Another if statement somewhere, perhaps?
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
for($start; $start <= $end; $start++) {
$answer = $start * $times;
print $start . " multiplied by " . $times . " = " . $answer . "
";
}
}
?>
Code Explanation
We need all those numbers from the textboxes on the form, so we start with:
$times = 2;
if (isset($_POST['Submit1'])) {
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
}
The first line just puts a value in the variable called $times . This is so that the "Multiply By" textbox will have a default value when the page is loaded.
Next we use the isset( ) function again, just to check if the user clicked the Submit button. This is exactly the same as you saw in the last section.
To get the values from the textboxes, we use the following:
$start = $_POST['txtStart'];
$end = $_POST['txtEnd'];
$times = $_POST['txtTimes'];
Again, this is code you met in the last section. You just assign the values from the textboxes to the new variables using $_POST[]. In between the square brackets, we've typed the NAME of the HTML textboxes. So this gives us the values that the user entered on the form. Next comes out For Loop:
for($start; $start <= $end; $start++) {
$answer = $start * $times;
}
Let's look at that first line again:
for($start; $start <= $end; $start++) {
So we have a starting value for our loop, an end value, and an update expression. The starting value is coming from the variable called $start. This will be whatever number the user entered in the first textbox. The default is 1. Look at the end value, though:
$start <= $end
The end value is when the value in the variable called $start is less than or equal to the value held in the variable called $end. This works because we're increasing the value of $start each time round the loop. The variable called $end is a fixed value, and comes from the textbox on the form.
The last part of the loop code is the update expression. This tells PHP to increase the value of $start each time round the loop:
$start++
The double plus symbol (++) means "add 1 to the number held in $start".
And that's the essence of for loops: provide a start value, an end value, and how you want to update each time round the loop.
The code inside the for loop, however, the code that gets executed each time round the loop, is this:
$answer = $start * $times;
Remember, the variable $times holds the times table, the 2 times table by default. This is being multiplied by whatever is inside the variable $start. Each time round the loop, $start will have a different value – first 1, then 2, then 3, etc. The answer is then stored in the variable that we called $answer. So it's really doing this:
$answer = 1 * 2;
$answer = 2 * 2;
$answer = 3 * 2;
etc
Finally, we displayed the result to the page like this:
print $start . " multiplied by " . $times . " = " . $answer . "
";
This is just concatenation. See if you can work out what all the parts do!
And that’s it – your very own times table generator. If you have children, show them the programme you wrote. They’ll be very impressed and tell you how brilliant you are. Children are like that.
Of course, your programme is not perfect, which I’m sure the children will discover. Especially if they enter a 10 as the start number and a 1 as the end number. Why doesn't it print anything out? Anything you can do to trap this error? Another if statement somewhere, perhaps?
A PHP "Times Table" Programme
In the previous part, you saw what a For Loop was. In this section, we'll write a times table programme to illustrate how for loops work.
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder). When loaded into the browser, it looks like this:
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder.). When loaded into the browser, it looks like this:
What we're going to do is to get the values from the textboxes and create a Times Table proramme. When the button is clicked, the output will be something like this:
In other words, when the button is clicked we'll print the Times Table to the page. You can have a different Times Table, depending on what values you enter in the textboxes. To make a start with the coding, move on to the next part.
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder). When loaded into the browser, it looks like this:
There's a script called timesTable.php amongst the files you downloaded (in the scripts folder.). When loaded into the browser, it looks like this:
What we're going to do is to get the values from the textboxes and create a Times Table proramme. When the button is clicked, the output will be something like this:
In other words, when the button is clicked we'll print the Times Table to the page. You can have a different Times Table, depending on what values you enter in the textboxes. To make a start with the coding, move on to the next part.
For Loops in PHP
So what’s a loop then? A loop is something that goes round and round. If I told you to move a finger around in a loop, you’d have no problem with the order (unless you have no fingers!) In programming, it’s exactly the same. Except a programming loop will go round and round until you tell it to stop. You also need to tell the programme two other things - where to start your loop, and what to do after it’s finished one lap (known as the update expression).
You can programme without using loops. But it’s an awful lot easier with them. Consider this.
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this
$answer = 1 + 2 + 3 + 4
print $answer
Fairly simple, you think. And not much code, either. But what if you wanted to add up a thousand numbers? Are you really going to type them all out like that? It’s an awful lot of typing. A loop would make life a lot simpler. You use them when you want to execute the same code over and over again.
We'll discuss a few flavours of programming loops, but as the For Loop is the most used type of loop, we'll discuss those first.
For Loops
Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run your code and test it out.
$counter = 0;
$start = 1;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "
";
}
?>
How did you get on? You should have seen the numbers 1 to 10 printed on your browser page.
The format for a For Loop is this:
for (start value; end value; update expression) {
}
The first thing you need to do is type the name of the loop you’re using, in this case for. In between round brackets, you then type your three conditions:
Start Value
The first condition is where you tell PHP the initial value of your loop. In other words, start the loop at what number? We used this:
$start = 1
We’re assigning a value of 1 to a variable called $start. Like all variables, you can make up your own name. A popular name for the initial variable is the letter i . You can set the initial condition before the loop begins, like we did:
$start = 1
for($start; $start < 11; $start++) {
Or you can assign your loop value right in the For Loop code:
for($start = 1; start < 11; start++) {
The result is the same – the start number for this loop is 1
End Value
Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable $start is Less Than 11.
for($start; $start < 11; $start++) {
When the value of $start is 11 or higher, PHP will bail out of the loop.
Update Expression
Loops need a way of getting the next number in a series. If the loop couldn’t update the starting value, it would be stuck on the starting value. If we didn’t update our start value, our loop would get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used this:
$start++
In a lot of programming language (and PHP) the double plus symbol (++) means increment (increase the value by one). It’s just a short way of saying this:
$start = $start + 1
You can go down by one (decrement) by using the double minus symbol (--), but we won’t go into that.
So our whole loop reads “Starting at a value of 1, keep going round and round while the start value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:
$counter = $counter + 1;
print $counter . "
";
Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly the same as what we’re doing with the start variable. So we could have put this instead:
$counter ++
The effect would be the same. As an experiment, try setting the value of $counter to 11 outside the loop (it’s currently $counter = 0). Then inside the loop, use $counter- - (the double minus sign). Can you guess what will happen? Will it crash, or not? Or will it print something out? Better save your work, just in case!
To get more practice with the For Loop, we'll write a little Times Table programme.
You can programme without using loops. But it’s an awful lot easier with them. Consider this.
You want to add up the numbers 1 to 4: 1 + 2 + 3 + 4. You could do it like this
$answer = 1 + 2 + 3 + 4
print $answer
Fairly simple, you think. And not much code, either. But what if you wanted to add up a thousand numbers? Are you really going to type them all out like that? It’s an awful lot of typing. A loop would make life a lot simpler. You use them when you want to execute the same code over and over again.
We'll discuss a few flavours of programming loops, but as the For Loop is the most used type of loop, we'll discuss those first.
For Loops
Here’s a PHP For Loop in a little script. Type it into new PHP script and save your work. Run your code and test it out.
$counter = 0;
$start = 1;
for($start; $start < 11; $start++) {
$counter = $counter + 1;
print $counter . "
";
}
?>
How did you get on? You should have seen the numbers 1 to 10 printed on your browser page.
The format for a For Loop is this:
for (start value; end value; update expression) {
}
The first thing you need to do is type the name of the loop you’re using, in this case for. In between round brackets, you then type your three conditions:
Start Value
The first condition is where you tell PHP the initial value of your loop. In other words, start the loop at what number? We used this:
$start = 1
We’re assigning a value of 1 to a variable called $start. Like all variables, you can make up your own name. A popular name for the initial variable is the letter i . You can set the initial condition before the loop begins, like we did:
$start = 1
for($start; $start < 11; $start++) {
Or you can assign your loop value right in the For Loop code:
for($start = 1; start < 11; start++) {
The result is the same – the start number for this loop is 1
End Value
Next, you have to tell PHP when to end your loop. This can be a number, a Boolean value, a string, etc. Here, we’re telling PHP to keep going round the loop while the value of the variable $start is Less Than 11.
for($start; $start < 11; $start++) {
When the value of $start is 11 or higher, PHP will bail out of the loop.
Update Expression
Loops need a way of getting the next number in a series. If the loop couldn’t update the starting value, it would be stuck on the starting value. If we didn’t update our start value, our loop would get stuck on 1. In other words, you need to tell the loop how it is to go round and round. We used this:
$start++
In a lot of programming language (and PHP) the double plus symbol (++) means increment (increase the value by one). It’s just a short way of saying this:
$start = $start + 1
You can go down by one (decrement) by using the double minus symbol (--), but we won’t go into that.
So our whole loop reads “Starting at a value of 1, keep going round and round while the start value is less than 11. Increase the starting value by one each time round the loop.”
Every time the loop goes round, the code between our two curly brackets { } gets executed:
$counter = $counter + 1;
print $counter . "
";
Notice that we’re just incrementing the counter variable by 1 each time round the loop, exactly the same as what we’re doing with the start variable. So we could have put this instead:
$counter ++
The effect would be the same. As an experiment, try setting the value of $counter to 11 outside the loop (it’s currently $counter = 0). Then inside the loop, use $counter- - (the double minus sign). Can you guess what will happen? Will it crash, or not? Or will it print something out? Better save your work, just in case!
To get more practice with the For Loop, we'll write a little Times Table programme.
PHP and HTML Checkboxes
Like Radio buttons, checkboxes are used to give visitors a choice of options. Whereas Radio Buttons restrict users to only one choice, you can select more than one option with Checkboxes.
Here's a page that asks users to choose which course books they want to order:
As you can see, five items can be selected. Only three are chosen at the moment. When the button is clicked you, as the programmer, want to do at least two things: record which checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of errors.
You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding. The same is true for checkboxes. Let's have a look at one solution to the problem.
Because the code is a little more complex, we've included it in the files you downloaded. The script you're looking for is checkboxes.php, and is in the scripts folder. Open it up and take a look at the code. Here it is in full, if you want to copy and paste it:
The Checkboxes Script
Note one thing about the HTML checkbox elements: they all have different NAME values (ch1, ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME. That's because only one option can be selected with Radio Buttons. Because the user can select more than one option with Checkboxes, it makes sense to give them different NAME values, and treat them as separate entities (but some advocate treating them just like Radio Buttons).
In your PHP code, the technique is to check whether each checkbox element has been checked or not. It's more or less the same as for the radio Buttons. First we set up five variable and set them all the unchecked, just like we did before:
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
The next thing is the same as well: check to see if the Submit button was clicked:
if (isset($_POST['Submit1'])) {
}
Inside of this code, however, we have another isset( ) function:
if (isset($_POST['ch1'])) {
}
This time, we're checking to see if a checkbox was set. We need to do this because of a peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is returned! If you try the code without checking if the checkboxes are set, then you'll have to deal with a lot of "Undefined" errors.
If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true. If the isset( ) function is true, then our code inside of the if statement gets executed:
if ($ch1 = = 'net') {
$ch1 = 'checked';
}
This is yet another If Statement! But we're just checking the value of a variable. We need to know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net' then execute some code.
The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The rest of the if statements are the same – one for each checkbox on the form.
The last thing we need to do is to print the value of the variable to the HTML form:
>Visual Basic .NET
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
So we're just printing what is inside of the variable called $ch1. This will either be "unchecked" or "checked",
There are other solution for checkboxes, but none seem simple! The point here, though, is that to get the job done we used Conditional Logic.
How to validate checkboxes using JavaScript
Another way to deal with checkboxes, though, is with some JavaScript. The following script was sent to us by Tapan Bhanot. It uses JavaScript to validate the checkboxes before sending it to a PHP script. Note how the checkboxes all have the same name on the HTML form, and that it is being posted to a PHP script called step2.php:
View Tapan's script (opens in a new window)
You'll learn more about dealing with HTML forms as we go along. For now, we'll leave the subject, and move on. It's a bit of a bumpy ride in the next part, though, as we're tackling loops!
Here's a page that asks users to choose which course books they want to order:
As you can see, five items can be selected. Only three are chosen at the moment. When the button is clicked you, as the programmer, want to do at least two things: record which checkboxes were ticked, and have PHP "remember" which items were chosen, just in case of errors.
You don't want the ticks disappearing from the checkboxes, if the user has failed to enter some other details incorrectly. We saw with Radio Buttons that this can involve some tricky coding. The same is true for checkboxes. Let's have a look at one solution to the problem.
Because the code is a little more complex, we've included it in the files you downloaded. The script you're looking for is checkboxes.php, and is in the scripts folder. Open it up and take a look at the code. Here it is in full, if you want to copy and paste it:
The Checkboxes Script
Note one thing about the HTML checkbox elements: they all have different NAME values (ch1, ch2 ch3, etc). When we coded for the Radio Buttons, we gave the buttons the same NAME. That's because only one option can be selected with Radio Buttons. Because the user can select more than one option with Checkboxes, it makes sense to give them different NAME values, and treat them as separate entities (but some advocate treating them just like Radio Buttons).
In your PHP code, the technique is to check whether each checkbox element has been checked or not. It's more or less the same as for the radio Buttons. First we set up five variable and set them all the unchecked, just like we did before:
$ch1 = 'unchecked';
$ch2 = 'unchecked';
$ch3 = 'unchecked';
$ch4 = 'unchecked';
$ch5 = 'unchecked';
The next thing is the same as well: check to see if the Submit button was clicked:
if (isset($_POST['Submit1'])) {
}
Inside of this code, however, we have another isset( ) function:
if (isset($_POST['ch1'])) {
}
This time, we're checking to see if a checkbox was set. We need to do this because of a peculiarity of HTML checkboxes. If they are not ticked, they have no value at all, so nothing is returned! If you try the code without checking if the checkboxes are set, then you'll have to deal with a lot of "Undefined" errors.
If the checkbox is ticked, though, it will return a value. And so the isset( ) function will be true. If the isset( ) function is true, then our code inside of the if statement gets executed:
if ($ch1 = = 'net') {
$ch1 = 'checked';
}
This is yet another If Statement! But we're just checking the value of a variable. We need to know what is inside of it. This one says, "If the value inside of the variable called $ch1 is 'net' then execute some code.
The code we need to execute is to put the text 'checked' inside of the variable called $ch1. The rest of the if statements are the same – one for each checkbox on the form.
The last thing we need to do is to print the value of the variable to the HTML form:
>Visual Basic .NET
Again, this is the same code you saw with the Radio Buttons. The PHP part is:
So we're just printing what is inside of the variable called $ch1. This will either be "unchecked" or "checked",
There are other solution for checkboxes, but none seem simple! The point here, though, is that to get the job done we used Conditional Logic.
How to validate checkboxes using JavaScript
Another way to deal with checkboxes, though, is with some JavaScript. The following script was sent to us by Tapan Bhanot. It uses JavaScript to validate the checkboxes before sending it to a PHP script. Note how the checkboxes all have the same name on the HTML form, and that it is being posted to a PHP script called step2.php:
View Tapan's script (opens in a new window)
You'll learn more about dealing with HTML forms as we go along. For now, we'll leave the subject, and move on. It's a bit of a bumpy ride in the next part, though, as we're tackling loops!
PHP and Radio Buttons
A Radio Button is a way to restrict users to having only one choice. Examples are : Male/Female, Yes/No, or answers to surveys and quizzes.
Here's a simple from with just two radio buttons and a Submit button:
You can find the code for the page above in the files you downloaded, in the scripts folder. The file is called radioButton.php. Open it up in your text editor. If you want to copy and paste it, click below.
The Radio Button Form
Make sure you save your work as radioButton.php, as that's where we're posting the Form – to itself.
To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML form elements. In the HTML above, the NAME of the Radio buttons is the same – "gender". The first Radio Button has a value of "male" and the second Radio Button has a value of female. When you're writing your PHP code, it's these values that are returned. Here's some PHP code. Add it to the HEAD section of your HTML:
$selected_radio = $_POST['gender'];
print $selected_radio;
?>
This is more or less the same code as we used for the text box! The only thing that's changed (apart from the variable name) is the NAME of the HTML form element we want to access – "gender". The last line just prints the value to the page. Again, though, we can add code to detect if the user clicked the Submit button:
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
}
Again, this is the same code you saw earlier – just access the form element called 'Submit1' and see if it is set. The code only executes if it is.
Try out the code. Select a radio button and click Submit button. The choice you made is printed to the page - either "male" or "female". What you will notice, however, when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. Again, PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little more complex than for text boxes
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
Did we say a little more complex? OK, it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first:
This is just a print statement. What is printed out is the value inside of the variable. What is inside of the variable will be either the word "checked" or the word "unchecked". Which it is depends on the logic from our long PHP at the top of the page. Let's break that down.
First we have two variables at the top of the code:
$male_status = 'unchecked';
$female_status = 'unchecked';
These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit button being clicked.
Next we have our check to see if Submit is clicked:
if (isset($_POST['Submit1'])) {
}
Exactly the same as before. As is the next line that puts which radio button was selected into the variable:
$selected_radio = $_POST['gender'];
We then need some conditional logic. We need to set a variable to "checked", so we have an if, else … if construction:
if ($selected_radio = = 'male') {
}
else if ($selected_radio = = 'female') {
}
All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one thing; if it's 'female', do another. But look at what we're doing:
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'.
So the code works because of the values inside of two variables: $male_status and $female_status.
Yes, the code is very messy – but radio Buttons can be a tad tricky, when you want to retain the value of the selected item. Speaking of tricky – checkboxes are up next!
Here's a simple from with just two radio buttons and a Submit button:
You can find the code for the page above in the files you downloaded, in the scripts folder. The file is called radioButton.php. Open it up in your text editor. If you want to copy and paste it, click below.
The Radio Button Form
Make sure you save your work as radioButton.php, as that's where we're posting the Form – to itself.
To get the value of a radio button with PHP code, again you access the NAME attribute of the HTML form elements. In the HTML above, the NAME of the Radio buttons is the same – "gender". The first Radio Button has a value of "male" and the second Radio Button has a value of female. When you're writing your PHP code, it's these values that are returned. Here's some PHP code. Add it to the HEAD section of your HTML:
$selected_radio = $_POST['gender'];
print $selected_radio;
?>
This is more or less the same code as we used for the text box! The only thing that's changed (apart from the variable name) is the NAME of the HTML form element we want to access – "gender". The last line just prints the value to the page. Again, though, we can add code to detect if the user clicked the Submit button:
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
print $selected_radio;
}
Again, this is the same code you saw earlier – just access the form element called 'Submit1' and see if it is set. The code only executes if it is.
Try out the code. Select a radio button and click Submit button. The choice you made is printed to the page - either "male" or "female". What you will notice, however, when you try out the code is that the dot disappears from your selected radio button after the Submit is clicked. Again, PHP is not retaining the value you selected. The solution for radio Buttons, though, is a little more complex than for text boxes
Radio buttons have another attribute - checked or unchecked. You need to set which button was selected by the user, so you have to write PHP code inside the HTML with these values - checked or unchecked. Here's one way to do it:
The PHP code:
$male_status = 'unchecked';
$female_status = 'unchecked';
if (isset($_POST['Submit1'])) {
$selected_radio = $_POST['gender'];
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
}
?>
The HTML FORM code:
Did we say a little more complex? OK, it's much more complex than any code you've written so far! Have a look at the PHP code inside the HTML first:
This is just a print statement. What is printed out is the value inside of the variable. What is inside of the variable will be either the word "checked" or the word "unchecked". Which it is depends on the logic from our long PHP at the top of the page. Let's break that down.
First we have two variables at the top of the code:
$male_status = 'unchecked';
$female_status = 'unchecked';
These both get set to unchecked. That's just in case the page is refreshed, rather than the Submit button being clicked.
Next we have our check to see if Submit is clicked:
if (isset($_POST['Submit1'])) {
}
Exactly the same as before. As is the next line that puts which radio button was selected into the variable:
$selected_radio = $_POST['gender'];
We then need some conditional logic. We need to set a variable to "checked", so we have an if, else … if construction:
if ($selected_radio = = 'male') {
}
else if ($selected_radio = = 'female') {
}
All we're doing is testing what is inside of the variable called $selected_radio. If it's 'male' do one thing; if it's 'female', do another. But look at what we're doing:
if ($selected_radio = = 'male') {
$male_status = 'checked';
}
else if ($selected_radio = = 'female') {
$female_status = 'checked';
}
If the 'male' button was clicked then set the $male_status variable to a value of 'checked'. If the 'female' option button was clicked then set the $female_status variable to a value of 'checked'.
So the code works because of the values inside of two variables: $male_status and $female_status.
Yes, the code is very messy – but radio Buttons can be a tad tricky, when you want to retain the value of the selected item. Speaking of tricky – checkboxes are up next!
Keeping the data the user entered PHP
In the previous sections, you've been following along and building up a HTML form. You've learned how to get the text from a text box on a form, but there is a problem.
When the basicForm.php form is submitted, the details that the user entered get erased. You're left with the VALUE that was set in the HTML. For us, username kept appearing in the text box when the button was clicked. You can keep the data the user entered quite easily.
Your script should now look like the one in the link below. If not copy and paste this script, and test it out on your server. (Save the script as basicForm.php.)
The basicForm.php script
If you look at the VALUE attribute of the text box in the HTML from the above script, you'll see that it's set to "username". Because the form gets posted back to itself, this value will keep re-appearing in the textbox when the page is submitted. Worse, if you've left the Value attributes empty then everything the user entered will disappear. This can be very annoying, if you're asking the user to try again. Better is to POST back the values that the user entered.
To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
VALUE=""
In other words, the VALUE attribute is now a PHP line of code. The line of code is just this:
print $username ;
?>
It's a bit hard to read, because it's all on one line.
You also need to amend your PHP code in the HEAD section to include an else statement:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else {
$username ="";
}
The new addition is in bold, red text. But in the else statement, we're just setting the value of the variable called $username for when the button is NOT clicked, i.e. when the page is refreshed.
However, there are some security issues associated with textboxes (and other form elements). So we'll see a more secure way to handle these in a later section.
But our new line of HTML for our textbox reads like this:
In other words, we're now printing out the VALUE attribute with PHP code.
Now that you know a few things about getting values from HTML forms, here's a few exercise
Exercise
Add two text boxes and a Submit button to a HTML form. Invite the user to enter a first name and surname. When the button is clicked, print out the person's full name. Don't worry about what is in the text boxes after the button is clicked.
Exercise
Using the same form as the previous exercise, display the first name and surname in the textboxes, instead of printing them out.
Exercise
Suppose your web site has only 5 users. Create a HTML form to check if a visitor is one of the 5 users. Display a suitable message.
In the next section, we'll take a look at how to handle Radion Buttons on a HTML Form.
When the basicForm.php form is submitted, the details that the user entered get erased. You're left with the VALUE that was set in the HTML. For us, username kept appearing in the text box when the button was clicked. You can keep the data the user entered quite easily.
Your script should now look like the one in the link below. If not copy and paste this script, and test it out on your server. (Save the script as basicForm.php.)
The basicForm.php script
If you look at the VALUE attribute of the text box in the HTML from the above script, you'll see that it's set to "username". Because the form gets posted back to itself, this value will keep re-appearing in the textbox when the page is submitted. Worse, if you've left the Value attributes empty then everything the user entered will disappear. This can be very annoying, if you're asking the user to try again. Better is to POST back the values that the user entered.
To post the details back to the form, and thus keep the data the user has already typed out, you can use this:
VALUE=""
In other words, the VALUE attribute is now a PHP line of code. The line of code is just this:
print $username ;
?>
It's a bit hard to read, because it's all on one line.
You also need to amend your PHP code in the HEAD section to include an else statement:
if (isset($_POST['Submit1'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
else {
$username ="";
}
The new addition is in bold, red text. But in the else statement, we're just setting the value of the variable called $username for when the button is NOT clicked, i.e. when the page is refreshed.
However, there are some security issues associated with textboxes (and other form elements). So we'll see a more secure way to handle these in a later section.
But our new line of HTML for our textbox reads like this:
In other words, we're now printing out the VALUE attribute with PHP code.
Now that you know a few things about getting values from HTML forms, here's a few exercise
Exercise
Add two text boxes and a Submit button to a HTML form. Invite the user to enter a first name and surname. When the button is clicked, print out the person's full name. Don't worry about what is in the text boxes after the button is clicked.
Exercise
Using the same form as the previous exercise, display the first name and surname in the textboxes, instead of printing them out.
Exercise
Suppose your web site has only 5 users. Create a HTML form to check if a visitor is one of the 5 users. Display a suitable message.
In the next section, we'll take a look at how to handle Radion Buttons on a HTML Form.
Setting ACTION to a different PHP Page php
You don't have to submit your form data to the same PHP page, as we've been doing. You can send it to an entirely different PHP page. To see how it works, try this:
Create the following page, and call it basicForm2.php. This is your HTML. Notice the ACTION attribue.
A BASIC HTML FORM
Now create the following page, and call it submitForm.php.
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
?>
In the PHP script above, notice how there's no HTML tags. And we've left out the code that checks if the Submit button was clicked. That's because there's no PHP left in the first page. The code only gets executed IF the Submit is clicked.
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But there is a problem with it, which you will have noticed: the script gets executed on a new page. That means your form will disappear!
We'll keep the PHP and HTML together. But there will be times when you do want to send form data to a different PHP page, as we'll see in later sections.
Create the following page, and call it basicForm2.php. This is your HTML. Notice the ACTION attribue.
Now create the following page, and call it submitForm.php.
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
?>
In the PHP script above, notice how there's no HTML tags. And we've left out the code that checks if the Submit button was clicked. That's because there's no PHP left in the first page. The code only gets executed IF the Submit is clicked.
Posting form data to a different PHP script is a way to keep the HTML and PHP separate. But there is a problem with it, which you will have noticed: the script gets executed on a new page. That means your form will disappear!
We'll keep the PHP and HTML together. But there will be times when you do want to send form data to a different PHP page, as we'll see in later sections.
Checking if the Submit Button of a HTML Form was Clicked php
In the previous section, you saw how to get text from a textbox when a Submit button on a form was clicked. However, when you first load the page the text still displays.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if (isset($_POST['Submit'])) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
The new addition is in bold, red text. Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!
Int he next part, you'll see how to submit your form data to a PHP script on a different page.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if (isset($_POST['Submit'])) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
The new addition is in bold, red text. Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!
Int he next part, you'll see how to submit your form data to a PHP script on a different page.
Checking if the Submit Button of a HTML Form was Clicked php
In the previous section, you saw how to get text from a textbox when a Submit button on a form was clicked. However, when you first load the page the text still displays.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if (isset($_POST['Submit'])) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
The new addition is in bold, red text. Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!
Int he next part, you'll see how to submit your form data to a PHP script on a different page.
The reason why the text displays when the page is first loaded is because the script executes whether the button is clicked or not. This is the problem you face when a PHP script is on the same page as the HTML, and is being submitted to itself in the ACTION attribute.
To get round this, you can do a simple check using another IF Statement. What you do is to check if the Submit button was clicked. If it was, then run your code. To check if a submit button was clicked, use this:
if (isset($_POST['Submit'])) { }
Now that looks a bit messy! But it actually consists of three parts:
if ( ) { }
isset( )
$_POST['Submit']
You know about the if statement. But in between the round brackets, we have isset( ). This is an inbuilt function that checks if a variable has been set or not. In between the round brackets, you type what you want isset( ) to check. For us, this is $_POST['Submit']. If the user just refreshed the page, then no value will be set for the Submit button. If the user did click the Submit button, then PHP will automatically return a value. Change you script from the previous page to the following and try it out:
if (isset($_POST['Submit'])) {
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
}
The new addition is in bold, red text. Make a note of where all those messy round, square and curly brackets are. Miss one out and you'll get an error!
Int he next part, you'll see how to submit your form data to a PHP script on a different page.
Getting values from a Text Box with PHP
If you've been following along from the previous sections then your basicForm.php now has a METHOD and ACTION set. We're going to use these to process text that a user has entered into a text box. The METHOD attribute tells you how form data is being sent, and the ACTION attribute tells you where it is being sent.
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME yet, so change your HTML to this:
The NAME of our textbox is "username". It's this name that we will be using in a PHP script.
To return data from a HTML form element, you use the following strange syntax:
$_POST['formElement_name'];
You can assign this to a variable:
$Your_Variable = $_POST['formElement_name'];
Before we explain all the syntax, add the following PHP script to the HTML code you have so far. Make sure to add it the HEAD section of your HTML (the part to add is in bold):
A BASIC HTML FORM
$username = $_POST['username'];
print ($username);
?>
Save your work again, and click the submit button to run your script. (Don't worry if you see an error message about "Undefined index". Click the button anyway.) You should see this appear above your text box:
Delete the text "username" from the textbox, and click the button again. Your new text should appear above the textbox. The text box itself, however, will still have "username" in it. This is because the text box is getting reset when the data is returned to the browser. The Value attribute of the text box is what is being displayed.
So how does it work?
The $_POST[] is an inbuilt function you can use to get POST data from a form. If you had METHOD = "GET" on your form, then you'd used this instead:
$username = $_GET['username'];
So you begin with a dollar sign ($) and an underscore character ( _ ). Next comes the METHOD you want to use, POST or GET. You need to type a pair of square brackets next. In between the square brackets, you type the NAME of your HTML form element – username, in our case.
$_POST['username'];
Of course, you need the semi-colon to complete the line.
Whatever the VALUE was for your HTML element is what gets returned. You can then assign this to a variable:
$username = $_POST['username'];
So PHP will look for a HTML form element with the NAME username. It then looks at the VALUE attribute for this form element. It returns this value for you to use and manipulate.
At the moment, all we're doing is returning what the user entered and printing it to the page. But we can use a bit of Conditional Logic to test what is inside of the variable. As an example, change your PHP to this:
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
We're now checking to see if the user entered the text "letmein". If so, the username is correct; if not, print another message.
Try it out an see what happens. When you first load the page, before you even click the button, you might see the text "You're not a member of this site" displayed above the textbox. That's because we haven't checked to see if the Submit button on the form was clicked.
In the next part, we'll see how to check if the Submit button was clicked.
To get at the text that a user entered into a text box, the text box needs a NAME attribute. You then tell PHP the NAME of the textbox you want to work with. Our text box hasn't got a NAME yet, so change your HTML to this:
The NAME of our textbox is "username". It's this name that we will be using in a PHP script.
To return data from a HTML form element, you use the following strange syntax:
$_POST['formElement_name'];
You can assign this to a variable:
$Your_Variable = $_POST['formElement_name'];
Before we explain all the syntax, add the following PHP script to the HTML code you have so far. Make sure to add it the HEAD section of your HTML (the part to add is in bold):
$username = $_POST['username'];
print ($username);
?>
Save your work again, and click the submit button to run your script. (Don't worry if you see an error message about "Undefined index". Click the button anyway.) You should see this appear above your text box:
Delete the text "username" from the textbox, and click the button again. Your new text should appear above the textbox. The text box itself, however, will still have "username" in it. This is because the text box is getting reset when the data is returned to the browser. The Value attribute of the text box is what is being displayed.
So how does it work?
The $_POST[] is an inbuilt function you can use to get POST data from a form. If you had METHOD = "GET" on your form, then you'd used this instead:
$username = $_GET['username'];
So you begin with a dollar sign ($) and an underscore character ( _ ). Next comes the METHOD you want to use, POST or GET. You need to type a pair of square brackets next. In between the square brackets, you type the NAME of your HTML form element – username, in our case.
$_POST['username'];
Of course, you need the semi-colon to complete the line.
Whatever the VALUE was for your HTML element is what gets returned. You can then assign this to a variable:
$username = $_POST['username'];
So PHP will look for a HTML form element with the NAME username. It then looks at the VALUE attribute for this form element. It returns this value for you to use and manipulate.
At the moment, all we're doing is returning what the user entered and printing it to the page. But we can use a bit of Conditional Logic to test what is inside of the variable. As an example, change your PHP to this:
$username = $_POST['username'];
if ($username = = "letmein") {
print ("Welcome back, friend!");
}
else {
print ("You're not a member of this site");
}
We're now checking to see if the user entered the text "letmein". If so, the username is correct; if not, print another message.
Try it out an see what happens. When you first load the page, before you even click the button, you might see the text "You're not a member of this site" displayed above the textbox. That's because we haven't checked to see if the Submit button on the form was clicked.
In the next part, we'll see how to check if the Submit button was clicked.
The Submit Button of a HTML FORM php
The HTML Submit button is used to submit form data to the script mentioned in the ACTION attribute. Here's ours:
"
"
The ACTION Attribute of HTML Forms php
The Action attribute is crucial. It means, "Where do you want the form sent?". If you miss it out, your form won't get sent anywhere. You can send the form data to another PHP script, the same PHP script, an email address, a CGI script, or any other form of script.
In PHP, a popular technique is to send the script to the same page that the form is on – send it to itself, in other words. We'll use that technique first, but you'll see both techniques in action.
So you need to change the form you have been creating in the previous sections, the one that should be called basicForm.php. Locate the following, and amend the ACTION line to this:
In PHP, a popular technique is to send the script to the same page that the form is on – send it to itself, in other words. We'll use that technique first, but you'll see both techniques in action.
So you need to change the form you have been creating in the previous sections, the one that should be called basicForm.php. Locate the following, and amend the ACTION line to this:
The POST Attribute of HTML Forms
In the previous section, you saw what happened in the browser's address bar when you used the GET method for Form data. The alternative to GET is to use POST. Change the first line of your FORM to this:
"
"
The POST Attribute of HTML Forms
In the previous section, you saw what happened in the browser's address bar when you used the GET method for Form data. The alternative to GET is to use POST. Change the first line of your FORM to this:
"
"
The Method Attribute of HTML Forms php
If you look at the first line of our form from the previous page, you'll notice a METHOD attribute:
The HTML Form php
If you know a little HTML, then you know that the FORM tags can be used to interact with your users. Things that can be added to a form are the likes of text boxes, radio buttons, check boxes, drop down lists, text areas, and submit buttons. A basic HTML form with a textbox and a Submit button looks like this:
A BASIC HTML FORM
We won't explain what all the HTML elements do, as this is a book on PHP. Some familiarity with the above is assumed. But we'll discuss the METHOD, ACTION and SUBMIT attributes in the form above, because they are important.
The above form can be found in the files you download. It's in the scripts folder, and is called basicForm.php. Use it as a template, if you like.
So, create the form above. Save your work as basicForm.php. (This name will be VERY important!) Start your server, and make sure the form loads ok in your browser. You should be able to see a text box and a Submit button. Here's what it should look like:
If a user comes to your site and has to login, for example, then you'll need to get the details from textboxes. Once you get the text that the user entered, you then test it against a list of your users (this list is usually stored on a database, which we'll see how to code for in a later section). First, you need to know about the HTML attributes METHOD, ACTION and SUBMIT. We'll explore these in the next few sections.
We won't explain what all the HTML elements do, as this is a book on PHP. Some familiarity with the above is assumed. But we'll discuss the METHOD, ACTION and SUBMIT attributes in the form above, because they are important.
The above form can be found in the files you download. It's in the scripts folder, and is called basicForm.php. Use it as a template, if you like.
So, create the form above. Save your work as basicForm.php. (This name will be VERY important!) Start your server, and make sure the form loads ok in your browser. You should be able to see a text box and a Submit button. Here's what it should look like:
If a user comes to your site and has to login, for example, then you'll need to get the details from textboxes. Once you get the text that the user entered, you then test it against a list of your users (this list is usually stored on a database, which we'll see how to code for in a later section). First, you need to know about the HTML attributes METHOD, ACTION and SUBMIT. We'll explore these in the next few sections.
Operator Precedence – a List
Here's a list of the operators you've met so far, and the order of precedence. This can make a difference, as we saw during the mathematical operators. Don't worry about these too much, unless you're convinced that your math or logical is correct. In which case, you might have to consult the following:
* / % Highest Precedence
+ - .
< <= > >=
= = = != =
&&
| |
And
XOR
OR Lowest Precedence
The only operators you haven't yet met on the list above are the = = = and != = operators.
In recent editions of PHP, two new operators have been introduced: the triple equals sign ( = = =) and an exclamation, double equals ( != =). These are used to test if one value has the same as another AND are of the same type. An example would be:
$number = 3;
$text = 'three';
if ($number = = = $text) {
print("Same");
}
else {
print("Not the same");
}
So this asks, "Do the variables match exactly?" Since one is text and the other is a number, the answer is "no", or false. We won't be using these operators much, if at all!
Ok, if all of that has given you a headache, let's move on to some practical work. In the next section, we'll take a look at HTML forms, and how to get data from them. This is so that we can do other things besides printing to the screen.
* / % Highest Precedence
+ - .
< <= > >=
= = = != =
&&
| |
And
XOR
OR Lowest Precedence
The only operators you haven't yet met on the list above are the = = = and != = operators.
In recent editions of PHP, two new operators have been introduced: the triple equals sign ( = = =) and an exclamation, double equals ( != =). These are used to test if one value has the same as another AND are of the same type. An example would be:
$number = 3;
$text = 'three';
if ($number = = = $text) {
print("Same");
}
else {
print("Not the same");
}
So this asks, "Do the variables match exactly?" Since one is text and the other is a number, the answer is "no", or false. We won't be using these operators much, if at all!
Ok, if all of that has given you a headache, let's move on to some practical work. In the next section, we'll take a look at HTML forms, and how to get data from them. This is so that we can do other things besides printing to the screen.
Boolean Values in PHP
A Boolean value is one that is in either of two states. They are known as True or False values, in programming. True is usually given a value of 1, and False is given a value of zero. You set them up just like other variables:
$true_value = 1;
$false_value = 0;
You can replace the 1 and 0 with the words "true" and "false" (without the quotes). But a note of caution, if you do. Try this script out, and see what happens:
You can replace the 1 and 0 with the words "true" and "false" (without the quotes). But a note of caution, if you do. Try this script out, and see what happens:
$true_value = true;
$false_value = false;
print ("true_value = " . $true_value);
print (" false_value = " . $false_value);
?>
What you should find is that the true_value will print "1", but the false_value won't print anything! Now replace true with 1 and false with 0, in the script above, and see what prints out.
Boolean values are very common in programming, and you often see this type of coding:
$true_value = true;
if ($true_value) {
print("that's true");
}
This is a shorthand way of saying "if $true_value holds a Boolean value of 1 then the statement is true". This is the same as:
if ($true_value = = 1) {
print("that's true");
}
The NOT operand is also used a lot with this kind of if statement:
$true_value = true;
if (!$true_value) {
print("that's true");
}
else {
print("that's not true");
}
You'll probably meet Boolean values a lot, during your programming life. It's worth getting the hang of them!
$true_value = 1;
$false_value = 0;
You can replace the 1 and 0 with the words "true" and "false" (without the quotes). But a note of caution, if you do. Try this script out, and see what happens:
You can replace the 1 and 0 with the words "true" and "false" (without the quotes). But a note of caution, if you do. Try this script out, and see what happens:
$true_value = true;
$false_value = false;
print ("true_value = " . $true_value);
print (" false_value = " . $false_value);
?>
What you should find is that the true_value will print "1", but the false_value won't print anything! Now replace true with 1 and false with 0, in the script above, and see what prints out.
Boolean values are very common in programming, and you often see this type of coding:
$true_value = true;
if ($true_value) {
print("that's true");
}
This is a shorthand way of saying "if $true_value holds a Boolean value of 1 then the statement is true". This is the same as:
if ($true_value = = 1) {
print("that's true");
}
The NOT operand is also used a lot with this kind of if statement:
$true_value = true;
if (!$true_value) {
print("that's true");
}
else {
print("that's not true");
}
You'll probably meet Boolean values a lot, during your programming life. It's worth getting the hang of them!
Logical Operators
As well as the PHP comparison operators you saw earlier, there's also something called Logical Operators. You typically use these when you want to test more than one condition at a time. For example, you could check to see whether the username and password are correct from the same If Statement. Here's the table of these Operands.
Operand Example Meaning
&& $variable1 && $variable2 Are both values true?
| | $variable1 | | $variable2 Is at least one value true?
AND $variable1 AND $variable2 Are both values true?
XOR $variable1 XOR $variable2 Is at least one value true, but NOT both?
OR $variable1 OR $variable2 Is at least one value true?
! !$variable1 Is NOT something
The new Operands are rather strange, if you're meeting them for the first time. A couple of them even do the same thing! They are very useful, though, so here's a closer look.
The && Operator
The && symbols mean AND. Use this if you need both values to be true, as in our username and password test. After all, you don't want to let people in if they just get the username right but not the password! Here's an example:
$username ='user';
$password ='password';
if ($username ='user' && $password ='password') {
print("Welcome back!");
}
else {
print("Invalid Login Detected");
}
The if statement is set up the same, but notice that now two conditions are being tested:
$username ='user' && $password ='password
This says, "If username is correct AND the password is ok, too, then let them in". Both conditions need to go between the round brackets of your if statement.
The | | Operator
The two straight lines mean OR. Use this symbol when you only need one of your conditions to be true. For example, suppose you want to grant a discount to people if they have spent more than 100 pounds OR they have a special key. Else they don't get any discount. You'd then code like this:
$total_spent =100;
$special_key ='SK12345';
if ($total_spent =100 | | $special_key ='SK12345') {
print("Discount Granted!");
}
else {
print("No discount for you!");
}
This time we're testing two conditions and only need ONE of them to be true. If either one of them is true, then the code gets executed. If they are both false, then PHP will move on.
AND and OR
These are the same as the first two! AND is the same as && and OR is the same as ||. There is a subtle difference, but as a beginner, you can simply replace this:
$username ='user' && $password ='password
With this
$username ='user' AND $password ='password
And this:
$total_spent =100 | | $special_key ='SK12345'
With this:
$total_spent =100 OR $special_key ='SK12345'
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read than ||.
The difference, incidentally, is to do with Operator Precedence. We touched on this when we discussed variables, earlier. Logical Operators have a pecking order, as well. The full table is coming soon!
XOR
You probably won't need this one too much. But it's used when you want to test if one value of two is true but NOT both. If both values are the same, then PHP sees the expression as false. If they are both different, then the value is true. Suppose you had to pick a winner between two contestants. Only one of them can win. It's an XOR situation!
$contestant_one = true;
$contestant_two = true;
if ($contestant_one XOR $contestant_two) {
print("Only one winner!");
}
else {
print("Both can't win!");
}
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT something else. You can also use it to reverse the value of a true or false value. For example, you want to reset a variable to true, if it's been set to false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value = = false) {
print(!$test_value);
}
The code above will print out the number 1! (You'll see why when we tackle Boolean values below.) What we're saying here is, "If $test_value is false then set it to what it's NOT." What it's NOT is true, so it will now get this value. A bit confused? It's a tricky one, but it can come in handy!
In the next part, we'll take a look at Boolean values.
Operand Example Meaning
&& $variable1 && $variable2 Are both values true?
| | $variable1 | | $variable2 Is at least one value true?
AND $variable1 AND $variable2 Are both values true?
XOR $variable1 XOR $variable2 Is at least one value true, but NOT both?
OR $variable1 OR $variable2 Is at least one value true?
! !$variable1 Is NOT something
The new Operands are rather strange, if you're meeting them for the first time. A couple of them even do the same thing! They are very useful, though, so here's a closer look.
The && Operator
The && symbols mean AND. Use this if you need both values to be true, as in our username and password test. After all, you don't want to let people in if they just get the username right but not the password! Here's an example:
$username ='user';
$password ='password';
if ($username ='user' && $password ='password') {
print("Welcome back!");
}
else {
print("Invalid Login Detected");
}
The if statement is set up the same, but notice that now two conditions are being tested:
$username ='user' && $password ='password
This says, "If username is correct AND the password is ok, too, then let them in". Both conditions need to go between the round brackets of your if statement.
The | | Operator
The two straight lines mean OR. Use this symbol when you only need one of your conditions to be true. For example, suppose you want to grant a discount to people if they have spent more than 100 pounds OR they have a special key. Else they don't get any discount. You'd then code like this:
$total_spent =100;
$special_key ='SK12345';
if ($total_spent =100 | | $special_key ='SK12345') {
print("Discount Granted!");
}
else {
print("No discount for you!");
}
This time we're testing two conditions and only need ONE of them to be true. If either one of them is true, then the code gets executed. If they are both false, then PHP will move on.
AND and OR
These are the same as the first two! AND is the same as && and OR is the same as ||. There is a subtle difference, but as a beginner, you can simply replace this:
$username ='user' && $password ='password
With this
$username ='user' AND $password ='password
And this:
$total_spent =100 | | $special_key ='SK12345'
With this:
$total_spent =100 OR $special_key ='SK12345'
It's up to you which you use. AND is a lot easier to read than &&. OR is a lot easier to read than ||.
The difference, incidentally, is to do with Operator Precedence. We touched on this when we discussed variables, earlier. Logical Operators have a pecking order, as well. The full table is coming soon!
XOR
You probably won't need this one too much. But it's used when you want to test if one value of two is true but NOT both. If both values are the same, then PHP sees the expression as false. If they are both different, then the value is true. Suppose you had to pick a winner between two contestants. Only one of them can win. It's an XOR situation!
$contestant_one = true;
$contestant_two = true;
if ($contestant_one XOR $contestant_two) {
print("Only one winner!");
}
else {
print("Both can't win!");
}
See if you can guess which of the two will print out, before running the script.
The ! Operator
This is known as the NOT operator. You use it test whether something is NOT something else. You can also use it to reverse the value of a true or false value. For example, you want to reset a variable to true, if it's been set to false, and vice versa. Here's some code to try:
$test_value = false;
if ($test_value = = false) {
print(!$test_value);
}
The code above will print out the number 1! (You'll see why when we tackle Boolean values below.) What we're saying here is, "If $test_value is false then set it to what it's NOT." What it's NOT is true, so it will now get this value. A bit confused? It's a tricky one, but it can come in handy!
In the next part, we'll take a look at Boolean values.
The PHP Switch Statement
In some earlier code, we tested a single variable that came from a drop-down list. A different picture was displayed on screen, depending on the value inside of the variable. A long list of if and else … if statements were used. A better option, if you have only one variable to test, is to use something called a switch statement. To see how switch statements work, study the following code:
$picture ='church';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'church':
print('Church Picture');
break;
}
?>
In the code above, we place the direct text "church" into the variable called $picture. It's this direct text that we want to check. We want to know what is inside of the variable, so that we can display the correct picture.
To test a single variable with a Switch Statement, the following syntax is used:
switch ($variable_name) {
case 'What_you_want_to_check_for':
//code here
break;
}
It looks a bit complex, so we'll break it down.
switch ($variable_name) {
You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you type the name of the variable you want to check. After the round brackets, you need a left curly bracket.
case 'What_you_want_to_check_for':
The word 'case' is used before each value you want to check for. In our code, a list of values was coming from a drop-down list. These value were: church and kitten, among others. These are the values we need after the word 'case'. After the the text or variable you want to check for, a colon is needed ( : ).
//code here
After the semi colon on the 'case' line, you type the code you want to execute. Needless to say, you'll get an error if you miss out any semi-colons at the end of your lines of code!
break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop down to the next case and check that. Use the word 'break' to get out of the Switch statement.
To see the Switch statement in action, there is a file called "selectPicture2.php" amongst the ones you downloaded (Go here, if you haven't yet downloaded the files for this course). It’s in the scripts folder. Try it out, if you like!
If you look at the last few lines of the Switch Statement in this file, you'll see something else you can add to your own code:
default:
print ("No Image Selected");
The default option is like the else from if … else. It's used when there could be other, unknown, options. A sort of "catch all" option.
In the next part, we'll take a look at something called Logial Operators.
$picture ='church';
switch ($picture) {
case 'kitten':
print('Kitten Picture');
break;
case 'church':
print('Church Picture');
break;
}
?>
In the code above, we place the direct text "church" into the variable called $picture. It's this direct text that we want to check. We want to know what is inside of the variable, so that we can display the correct picture.
To test a single variable with a Switch Statement, the following syntax is used:
switch ($variable_name) {
case 'What_you_want_to_check_for':
//code here
break;
}
It looks a bit complex, so we'll break it down.
switch ($variable_name) {
You Start with the word 'Switch' then a pair of round brackets. Inside of the round brackets, you type the name of the variable you want to check. After the round brackets, you need a left curly bracket.
case 'What_you_want_to_check_for':
The word 'case' is used before each value you want to check for. In our code, a list of values was coming from a drop-down list. These value were: church and kitten, among others. These are the values we need after the word 'case'. After the the text or variable you want to check for, a colon is needed ( : ).
//code here
After the semi colon on the 'case' line, you type the code you want to execute. Needless to say, you'll get an error if you miss out any semi-colons at the end of your lines of code!
break;
You need to tell PHP to "Break out" of the switch statement. If you don't, PHP will simply drop down to the next case and check that. Use the word 'break' to get out of the Switch statement.
To see the Switch statement in action, there is a file called "selectPicture2.php" amongst the ones you downloaded (Go here, if you haven't yet downloaded the files for this course). It’s in the scripts folder. Try it out, if you like!
If you look at the last few lines of the Switch Statement in this file, you'll see something else you can add to your own code:
default:
print ("No Image Selected");
The default option is like the else from if … else. It's used when there could be other, unknown, options. A sort of "catch all" option.
In the next part, we'll take a look at something called Logial Operators.
What these mean: <= >=
We can use the same code you created in the previous section to illustrate "Less Than or Equal To" and "Greater Than or Equal To". Change this line in your code:
$total_spent = 90;
to this:
$total_spent = 100;
Now run your code again. Did anything print?
The reason why nothing printed, and no errors occurred, is because we haven't written any condition logic to test for equality. We're only checking to see if the two variables are either Less Than ( < ) each other, or Greater Than ( > ) each other. We need to check if they are the same (as they now are).
Instead of adding yet another else if part, checking to see if the two totals are equal, we can use the operators <= (Less Than or Equal To) or >= (Greater Than or Equal To). Here's how. Change this line in your code:
else if($total_spent < $discount_total) {
to this:
else if($total_spent <= $discount_total) {
The only thing that's changed is the Less Than or Equal to symbol has been used instead of just the Less Than sign.
Now run your code again. Because we're now saying "If total spent is Less Than or equal to discount total, then execute the code." So the text gets printed to the screen.
Exercise
Suppose you want to apply the discount if 100 pounds or more has been spent. Change your code above to display the correct message. Use the >= symbol for this exercise.
Comparison Operators can take a little getting used, but are well worth the effort. If you're having a hard time with all these Operands, you'll be glad to hear that there's even more of them! Before we get to them, though, let's take a look at another logic technique you can use – the Switch Statement.
$total_spent = 90;
to this:
$total_spent = 100;
Now run your code again. Did anything print?
The reason why nothing printed, and no errors occurred, is because we haven't written any condition logic to test for equality. We're only checking to see if the two variables are either Less Than ( < ) each other, or Greater Than ( > ) each other. We need to check if they are the same (as they now are).
Instead of adding yet another else if part, checking to see if the two totals are equal, we can use the operators <= (Less Than or Equal To) or >= (Greater Than or Equal To). Here's how. Change this line in your code:
else if($total_spent < $discount_total) {
to this:
else if($total_spent <= $discount_total) {
The only thing that's changed is the Less Than or Equal to symbol has been used instead of just the Less Than sign.
Now run your code again. Because we're now saying "If total spent is Less Than or equal to discount total, then execute the code." So the text gets printed to the screen.
Exercise
Suppose you want to apply the discount if 100 pounds or more has been spent. Change your code above to display the correct message. Use the >= symbol for this exercise.
Comparison Operators can take a little getting used, but are well worth the effort. If you're having a hard time with all these Operands, you'll be glad to hear that there's even more of them! Before we get to them, though, let's take a look at another logic technique you can use – the Switch Statement.
How to use "Less Than" and "Greater Than" in PHP
The Less Than ( < ) and Greater Than ( > ) symbols come in quite handy. They are really useful in loops (which we'll deal with in another section), and for testing numbers in general.
Suppose you wanted to test if someone has spent more than 100 pounds on your site. If they do, you want to give them a ten percent discount. The Less Than and Greater Than symbols can be used. Try this script. Open up your text editor, and type the following. Save your work, and try it out on your server.
$total_spent = 110;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
?>
By using the great Than symbol ( > ), we're saying "If the total spent is greater than the discount total then execute some code."
The Less than symbol can be used in the same way. Change your script to this (new lines are in bold, red text):
$total_spent = 90;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
else if($total_spent < $discount_total) {
print("Sorry – No discount!");
}
?>
In the else if part added above, we're checking to see if the total spent is Less Than ( < )100 pounds. If it is, then a new message is display. Notice that the $total_spent variable has been reduced to 90.
There is a problem with scripts such as the ones above, however. In the next part, we'll take a look at the operators for Less Than or Equal To and Greater Than or Equal To.
Suppose you wanted to test if someone has spent more than 100 pounds on your site. If they do, you want to give them a ten percent discount. The Less Than and Greater Than symbols can be used. Try this script. Open up your text editor, and type the following. Save your work, and try it out on your server.
$total_spent = 110;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
?>
By using the great Than symbol ( > ), we're saying "If the total spent is greater than the discount total then execute some code."
The Less than symbol can be used in the same way. Change your script to this (new lines are in bold, red text):
$total_spent = 90;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
else if($total_spent < $discount_total) {
print("Sorry – No discount!");
}
?>
In the else if part added above, we're checking to see if the total spent is Less Than ( < )100 pounds. If it is, then a new message is display. Notice that the $total_spent variable has been reduced to 90.
There is a problem with scripts such as the ones above, however. In the next part, we'll take a look at the operators for Less Than or Equal To and Greater Than or Equal To.
Not Equal To
In the previous section, you saw what Comparison Operators were. In this lessons, we'll explore the Comparison Operator for Not Equal To: !=.
So open up your text editor, and add the following script:
$correct_username = 'logmein';
$what_visitor_typed = 'logMEin';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
?>
Save your work and try it out. You should be able to guess what it does! But the thing to note here is the new Comparison Operator. Instead of using the double equals sign we’re now using an exclamation mark and a single equals sign. The rest of the If Statement is exactly the same format as you used earlier.
The things you’re trying to compare need to be different before a value of true is returned by PHP. In the second variable ($what_visitor_typed), the letters “ME” are in uppercase; in the first variable, they are in lowercase. So the two are not the same. Because we used the NOT equal to operator, the text will get printed. Change your script to this:
$correct_username = 'logmein';
$what_visitor_typed = 'logmein';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
else {
print("Welcome back, friend!");
}
See if you can figure out what has changed. Before you run the script, what will get printed out?
In the next part, we'll have a look at how to use the Less Than ( < ) and Greater Than ( > ) operators.
So open up your text editor, and add the following script:
$correct_username = 'logmein';
$what_visitor_typed = 'logMEin';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
?>
Save your work and try it out. You should be able to guess what it does! But the thing to note here is the new Comparison Operator. Instead of using the double equals sign we’re now using an exclamation mark and a single equals sign. The rest of the If Statement is exactly the same format as you used earlier.
The things you’re trying to compare need to be different before a value of true is returned by PHP. In the second variable ($what_visitor_typed), the letters “ME” are in uppercase; in the first variable, they are in lowercase. So the two are not the same. Because we used the NOT equal to operator, the text will get printed. Change your script to this:
$correct_username = 'logmein';
$what_visitor_typed = 'logmein';
if ($what_visitor_typed != $correct_username) {
print("You're not a valid user of this site!");
}
else {
print("Welcome back, friend!");
}
See if you can figure out what has changed. Before you run the script, what will get printed out?
In the next part, we'll have a look at how to use the Less Than ( < ) and Greater Than ( > ) operators.
Comparison Operators in PHP
You saw in the last section how to test what is inside of a variable. You used if, else … if, and else. You used the double equals sign (==) to test whether the variable was the same thing as some direct text. The double equals sign is known as a Comparison Operator. There a few more of these “operands” to get used. Here’s a list. Take a look, and then we’ll see a few examples of how to use them.
Operand Example Meaning
== $variable1 == $variable2 Has the same value as
!= $variable1 != $variable2 Does NOT have the same value as
< $variable1 < $variable2 Less Than
> $variable1 > $variable2 Greater Than
<= $variable1 <= $variable2 Less than or equals to
>= $variable1 >= $variable2 Greater than or equals to
Here's some more information on the above Operands.
= = (Has the same value as)
The double equals sign can mean “Has a value of” or "Has the same value as”. In the example below, the variable called $variable1 is being compared to the variable called $variable2
if ($variable1 == $variable2) {
}
!= (Does NOT have the same value as)
You can also test if one condition is NOT the same as another. In which case, you need the exclamation mark/equals sign combination ( != ). If you were testing for a genuine username, for example, you could say:
if ($what_user_entered != $username) {
print("You're not a valid user of this site!")
}
The above code says, “If what the user entered is NOT the same as the value in the variable called $username then print something out.
< (Less Than)
You'll want to test if one value is less than another. Use the left angle bracket for this ( < )
> (Greater Than)
You'll also want to test if one value is greater than another. Use the right angle bracket for this ( > )
<= (Less than or equals to)
For a little more precision, you can test to see if one variable is less than or equal to another. Use the left angle bracket followed by the equals sign ( <= )
>= (Greater than or equals to)
If you need to test if one variable is greater than or equal to another, use the right angle bracket followed by the equals sign ( >= )
In the next few sections, you'll see some examples of how to use the comparison operators. You've already used the double equals sign, so we'll start with "Not equal to".
Operand Example Meaning
== $variable1 == $variable2 Has the same value as
!= $variable1 != $variable2 Does NOT have the same value as
< $variable1 < $variable2 Less Than
> $variable1 > $variable2 Greater Than
<= $variable1 <= $variable2 Less than or equals to
>= $variable1 >= $variable2 Greater than or equals to
Here's some more information on the above Operands.
= = (Has the same value as)
The double equals sign can mean “Has a value of” or "Has the same value as”. In the example below, the variable called $variable1 is being compared to the variable called $variable2
if ($variable1 == $variable2) {
}
!= (Does NOT have the same value as)
You can also test if one condition is NOT the same as another. In which case, you need the exclamation mark/equals sign combination ( != ). If you were testing for a genuine username, for example, you could say:
if ($what_user_entered != $username) {
print("You're not a valid user of this site!")
}
The above code says, “If what the user entered is NOT the same as the value in the variable called $username then print something out.
< (Less Than)
You'll want to test if one value is less than another. Use the left angle bracket for this ( < )
> (Greater Than)
You'll also want to test if one value is greater than another. Use the right angle bracket for this ( > )
<= (Less than or equals to)
For a little more precision, you can test to see if one variable is less than or equal to another. Use the left angle bracket followed by the equals sign ( <= )
>= (Greater than or equals to)
If you need to test if one variable is greater than or equal to another, use the right angle bracket followed by the equals sign ( >= )
In the next few sections, you'll see some examples of how to use the comparison operators. You've already used the double equals sign, so we'll start with "Not equal to".
if … else if Statements in PHP
You can also add “else if” parts to the If Statements you've been exploring in the previous sections. The syntax is this:
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");
}
else if ($church_image == 1){
print ("
");
}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("
");
}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
Then run your code again. What do you expect to happen?
As a nice example of if statements, there is a file called “selectPicture.php” in the files that you downloaded. It’s in the scripts folder. Copy this to your own www (root) folder. As long as you have all the images mentioned in the script, they should display. But examine the code for the script (ignore the HTML form tags for now). What it does is to display an image, based on what the user selected from a drop down list. If statements are being used to test what is inside of a single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re doing is testing what is inside of the variable called $picture. We’re then displaying the image that corresponds to the word held in the variable.
Since you will be using if statements a heck of lot in your coding career, it’s essential that you have a good grasp of how to use them. To help you along, there’s some more about Conditional logic in the next section!
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");}
else if ($church_image == 1){
print ("
");}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("
");}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
Then run your code again. What do you expect to happen?
As a nice example of if statements, there is a file called “selectPicture.php” in the files that you downloaded. It’s in the scripts folder. Copy this to your own www (root) folder. As long as you have all the images mentioned in the script, they should display. But examine the code for the script (ignore the HTML form tags for now). What it does is to display an image, based on what the user selected from a drop down list. If statements are being used to test what is inside of a single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re doing is testing what is inside of the variable called $picture. We’re then displaying the image that corresponds to the word held in the variable.
Since you will be using if statements a heck of lot in your coding career, it’s essential that you have a good grasp of how to use them. To help you along, there’s some more about Conditional logic in the next section!
if … else if Statements in PHP
You can also add “else if” parts to the If Statements you've been exploring in the previous sections. The syntax is this:
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");
}
else if ($church_image == 1){
print ("
");
}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("
");
}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
Then run your code again. What do you expect to happen?
As a nice example of if statements, there is a file called “selectPicture.php” in the files that you downloaded. It’s in the scripts folder. Copy this to your own www (root) folder. As long as you have all the images mentioned in the script, they should display. But examine the code for the script (ignore the HTML form tags for now). What it does is to display an image, based on what the user selected from a drop down list. If statements are being used to test what is inside of a single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re doing is testing what is inside of the variable called $picture. We’re then displaying the image that corresponds to the word held in the variable.
Since you will be using if statements a heck of lot in your coding career, it’s essential that you have a good grasp of how to use them. To help you along, there’s some more about Conditional logic in the next section!
else if (another_condition_to_test) {
}
Change your code to this, to see how else if works:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");}
else if ($church_image == 1){
print ("
");}
else {
print ("No value of 1 detected");
}
?>
Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):
else if ($church_image == 1){
print ("
");}
What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.
To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:
if ($kitten_image == 1) {
}
else if ($church_image == 1) {
}
else {
}
You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:
$kitten_image = 1;
$church_image = 0;
to this:
$kitten_image = 0;
$church_image = 0;
Then run your code again. What do you expect to happen?
As a nice example of if statements, there is a file called “selectPicture.php” in the files that you downloaded. It’s in the scripts folder. Copy this to your own www (root) folder. As long as you have all the images mentioned in the script, they should display. But examine the code for the script (ignore the HTML form tags for now). What it does is to display an image, based on what the user selected from a drop down list. If statements are being used to test what is inside of a single variable.
Don’t worry too much about the rest of the code: concentrate on the if statements. All we’re doing is testing what is inside of the variable called $picture. We’re then displaying the image that corresponds to the word held in the variable.
Since you will be using if statements a heck of lot in your coding career, it’s essential that you have a good grasp of how to use them. To help you along, there’s some more about Conditional logic in the next section!
if … else Statements in PHP
Instead of using two if statements, as in the previous lesson, we can use an if ... else statement. Like this:
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("
");
}
else {
print ("
");
}
?>
Copy this new script, save your work, and try it out. You should find that the church image displays in the browser. This time, an if … else statement is being used. Let’s see how it works.
The syntax for the if else statement is this:
if (condition_to_test) {
}
else {
}
If you look at it closely, you’ll see that you have a normal If Statement first, followed by an “else” part after it. Here’s the “else” part:
else {
}
Again, the left and right curly brackets are used. In between the curly brackets, you type the code you want to execute. In our code, we set up two variables:
$kitten_image = 0;
$church_image = 1;
The variable called $kitten_image has been assigned a value of 0, and the variable called $church_image has been assigned a value of 1. The first line of the if statement tests to see what is inside of the variable called $kitten_image. It’s testing to see whether this variable has a value of 1.
if ($kitten_image == 1) {
What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable $kitten_image holds a value of 0, so PHP sees this as not true. Because a value of “not true” has been returned (false, if you like), PHP ignores the line of code for the if statement. Instead, it will execute the code for the “else” part. It doesn’t need to do any testing – else means “when all other options have been exhausted, run the code between the else curly brackets.“ For us, that was this:
else {
print ("
");
}
So the church image gets displayed. Change your two variables from this:
$kitten_image = 0;
$church_image = 1;
To this:
$kitten_image = 1;
$church_image = 0;
Run your code again and watch what happens. You should see the kitten! But can you work out why?
In the next section, we'll take a look at if ... else if statements.
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("
");}
else {
print ("
");}
?>
Copy this new script, save your work, and try it out. You should find that the church image displays in the browser. This time, an if … else statement is being used. Let’s see how it works.
The syntax for the if else statement is this:
if (condition_to_test) {
}
else {
}
If you look at it closely, you’ll see that you have a normal If Statement first, followed by an “else” part after it. Here’s the “else” part:
else {
}
Again, the left and right curly brackets are used. In between the curly brackets, you type the code you want to execute. In our code, we set up two variables:
$kitten_image = 0;
$church_image = 1;
The variable called $kitten_image has been assigned a value of 0, and the variable called $church_image has been assigned a value of 1. The first line of the if statement tests to see what is inside of the variable called $kitten_image. It’s testing to see whether this variable has a value of 1.
if ($kitten_image == 1) {
What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable $kitten_image holds a value of 0, so PHP sees this as not true. Because a value of “not true” has been returned (false, if you like), PHP ignores the line of code for the if statement. Instead, it will execute the code for the “else” part. It doesn’t need to do any testing – else means “when all other options have been exhausted, run the code between the else curly brackets.“ For us, that was this:
else {
print ("
");}
So the church image gets displayed. Change your two variables from this:
$kitten_image = 0;
$church_image = 1;
To this:
$kitten_image = 1;
$church_image = 0;
Run your code again and watch what happens. You should see the kitten! But can you work out why?
In the next section, we'll take a look at if ... else if statements.
Using If Statements in PHP
We can use an if statement to display our image, from the previous section. If the user selected "church", then display the church image. If the user selected "kitten", then display anoth image (the kitten image, which is also in your images folder). Here's some code:
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");
}
?>
Type that out, and save it as testImages.php. (Notice how there's no HTML!)
When you run the script, the kitten image should display. Let's look at the code and see what's happening.
The first two lines just set up some variables:
$kitten_image = 1;
$church_image = 0;
A value of 1 has been assigned to the variable called $kitten_image. A value of 0 has been assigned to the variable called $church_image. Then we have our if statement. Here it is without the print statement:
if ($kitten_image == 1) {
}
Notice how there's no semi-colon at the end of the first line - you don't need one. After the word "if" we have a round bracket. Then comes our variable name: $kitten_image. We want to test what's inside of this variable. Specifically, we want to test if it has a value of 1. So we need the double equals sign (==). The double equals sign doesn’t really mean “equals”. It means “has a value of”.
What we want to say is:
"If the variable called $kitten_image has a value of 1 then execute some code."
To complete the first line of the if statement we have another round bracket, and a left curly bracket. Miss any of these out, and you'll probably get the dreaded parse error!
The code we want to execute, though, is the print statement, so that our kitten image will display. This goes inside of the if statement:
if ($kitten_image == 1) {
print ("
");
}
You need the semi-colon at the end of the print statement.
But if your if statement only runs to one line, you can just do this:
if ($kitten_image == 1) { print ("
"); }
In other words, keep everything on one line. PHP doesn't care about your spaces, so it's perfectly acceptable code. Not very readable, but acceptable!
To make use of the church image, here's some new code to try:
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("
");
}
if ($church_image == 1) {
print ("
");
}
?>
Notice that the $kitten_image variable now has a value of 0 and that $church_image is 1. The new if statement is just the same as the first. When you run the script, however, the church image will display. That's because of this line:
if ($kitten_image == 1) {
That says, "If the variable called $kitten_image has a value of 1 ... ". PHP doesn't bother reading the rest of the if statement, because $kitten_image has a value of 0. It will jump down to our second if statement and test that:
if ($church_image == 1) {
Since the variable called $church_image does indeed have a value of 1, then the code inside of the if statement gets executed. That code prints out the HTML for the church image:
print ("
");
In the next section, we'll take a look at if ... else statements.
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("
");}
?>
Type that out, and save it as testImages.php. (Notice how there's no HTML!)
When you run the script, the kitten image should display. Let's look at the code and see what's happening.
The first two lines just set up some variables:
$kitten_image = 1;
$church_image = 0;
A value of 1 has been assigned to the variable called $kitten_image. A value of 0 has been assigned to the variable called $church_image. Then we have our if statement. Here it is without the print statement:
if ($kitten_image == 1) {
}
Notice how there's no semi-colon at the end of the first line - you don't need one. After the word "if" we have a round bracket. Then comes our variable name: $kitten_image. We want to test what's inside of this variable. Specifically, we want to test if it has a value of 1. So we need the double equals sign (==). The double equals sign doesn’t really mean “equals”. It means “has a value of”.
What we want to say is:
"If the variable called $kitten_image has a value of 1 then execute some code."
To complete the first line of the if statement we have another round bracket, and a left curly bracket. Miss any of these out, and you'll probably get the dreaded parse error!
The code we want to execute, though, is the print statement, so that our kitten image will display. This goes inside of the if statement:
if ($kitten_image == 1) {
print ("
");}
You need the semi-colon at the end of the print statement.
But if your if statement only runs to one line, you can just do this:
if ($kitten_image == 1) { print ("
"); }In other words, keep everything on one line. PHP doesn't care about your spaces, so it's perfectly acceptable code. Not very readable, but acceptable!
To make use of the church image, here's some new code to try:
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("
");}
if ($church_image == 1) {
print ("
");}
?>
Notice that the $kitten_image variable now has a value of 0 and that $church_image is 1. The new if statement is just the same as the first. When you run the script, however, the church image will display. That's because of this line:
if ($kitten_image == 1) {
That says, "If the variable called $kitten_image has a value of 1 ... ". PHP doesn't bother reading the rest of the if statement, because $kitten_image has a value of 0. It will jump down to our second if statement and test that:
if ($church_image == 1) {
Since the variable called $church_image does indeed have a value of 1, then the code inside of the if statement gets executed. That code prints out the HTML for the church image:
print ("
");In the next section, we'll take a look at if ... else statements.
If Statements in PHP
You saw in the last section that variables are storage areas for your text and numbers. But the reason you are storing this information is so that you can do something with them. If you have stored a username in a variable, for example, you'll then need to check if this is a valid username. To help you do the checking, something called Conditional Logic comes in very handy indeed. In this section, we'll take a look at just what Conditional Logic is. In the next section, we'll do some practical work.
Conditional Logic
Conditional Logic is all about asking "What happens IF ... ". When you press a button labelled "Don't Press this Button - Under any circumstance!" you are using Conditional Logic. You are asking, "Well, what happens IF I do press the button?"
You use Conditional Logic in your daily life all the time:
"If I turn the volume up on my stereo, will the neighbours be pleased?"
"If spend all my money on a new pair of shoes, will it make me happy?"
"If I study this course, will it improve my web site?"
Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test what is inside of a variable. You can then makes decisions based on what is inside of the variable. As an example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name. You would use some Conditional Logic to test whether or not the variable $User_Name really does contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
In PHP, you use the "IF" word like this:
if ($User_Name = = "authentic") {
//Code to let user access the site here;
}
Without any checking, the if statement looks like this:
if ( ) {
}
You can see it more clearly, here. To test a variable or condition, you start with the word "if". You then have a pair of round brackets. You also need some more brackets - curly ones. These are just to the right of the letter "P" on your keyboard (Well, a UK keyboard, anyway). You need the left curly bracket first { and then the right curly bracket } at the end of your if statement. Get them the wrong way round, and PHP refuses to work. This will get you an error:
if ($User_Name = = "authentic") }
//Code to Let user access the site here;
{
And so will this:
if ($User_Name = = "authentic") {
//Code to Let user access the site here;
{
The first one has the curly brackets the wrong way round (should be left then right), while the second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example above, we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if statement is this:
if (Condition_or_Variable_to_test) {
//your code here;
}
In the next lesson, we'll use if statements to display an image on the page.
We'll use the print statement to "print out" HTML code. As an example, take the following HTML code to display an image:

Just plain HTML. But you can put that code inside of the print statement:
print ("
");
When you run the code, the image should display. Of course, you'll need an image called church.jpg, and in a folder called images.
You can find these amongst the files you can download for this course, in the folder called images. (Go here to get the course files, if you haven't already.)
Copy the images folder to your www (root) directory. Then try the following script:
print ("
");
?>
Save your script to the same folder as the images folder (though NOT inside the images folder). Now fire up your server, and give it a try. Hopefully, you'll see the church image display, as in the following graphic:
Church Image (click to open in a new window 80K)
To clarify things, let's have some more practical example of If Statements.
Conditional Logic
Conditional Logic is all about asking "What happens IF ... ". When you press a button labelled "Don't Press this Button - Under any circumstance!" you are using Conditional Logic. You are asking, "Well, what happens IF I do press the button?"
You use Conditional Logic in your daily life all the time:
"If I turn the volume up on my stereo, will the neighbours be pleased?"
"If spend all my money on a new pair of shoes, will it make me happy?"
"If I study this course, will it improve my web site?"
Conditional Logic uses the "IF" word a lot. For the most part, you use Conditional Logic to test what is inside of a variable. You can then makes decisions based on what is inside of the variable. As an example, think about the username again. You might have a variable like this:
$User_Name = "My_Regular_Visitor";
The text "My_Regular_Visitor" will then be stored inside of the variable called $User_Name. You would use some Conditional Logic to test whether or not the variable $User_Name really does contain one of your regular visitors. You want to ask:
"IF $User_Name is authentic, then let $User_Name have access to the site."
In PHP, you use the "IF" word like this:
if ($User_Name = = "authentic") {
//Code to let user access the site here;
}
Without any checking, the if statement looks like this:
if ( ) {
}
You can see it more clearly, here. To test a variable or condition, you start with the word "if". You then have a pair of round brackets. You also need some more brackets - curly ones. These are just to the right of the letter "P" on your keyboard (Well, a UK keyboard, anyway). You need the left curly bracket first { and then the right curly bracket } at the end of your if statement. Get them the wrong way round, and PHP refuses to work. This will get you an error:
if ($User_Name = = "authentic") }
//Code to Let user access the site here;
{
And so will this:
if ($User_Name = = "authentic") {
//Code to Let user access the site here;
{
The first one has the curly brackets the wrong way round (should be left then right), while the second one has two left curly brackets.
In between the two round brackets, you type the condition you want to test. In the example above, we're testing to see whether the variable called $User_Name has a value of "authentic":
($User_Name = = "authentic")
Again, you'll get an error if you don't get your round brackets right! So the syntax for the if statement is this:
if (Condition_or_Variable_to_test) {
//your code here;
}
In the next lesson, we'll use if statements to display an image on the page.
We'll use the print statement to "print out" HTML code. As an example, take the following HTML code to display an image:

Just plain HTML. But you can put that code inside of the print statement:
print ("
");When you run the code, the image should display. Of course, you'll need an image called church.jpg, and in a folder called images.
You can find these amongst the files you can download for this course, in the folder called images. (Go here to get the course files, if you haven't already.)
Copy the images folder to your www (root) directory. Then try the following script:
print ("
");?>
Save your script to the same folder as the images folder (though NOT inside the images folder). Now fire up your server, and give it a try. Hopefully, you'll see the church image display, as in the following graphic:
Church Image (click to open in a new window 80K)
To clarify things, let's have some more practical example of If Statements.
Floating Point Numbers in PHP
A floating point number is one that has a dot in it, like 0.5 and 10.8. You don't need any special syntax to set these types of numbers up. Here's an example for you to try:
$first_number = 1.2;
$second_number = 2.5;
$sum_total = $second_number + $first_number;
print ($sum_total);
?>
You add up, subtract, divide and multiply these numbers in exactly the same way as the integers you've been using. A warning comes with floating point numbers, though: you shouldn't trust them, if you're after a really, really precise answer!
Some Exercises
To round up this section on number variables, here's a few exercises (In your print statements, there should be no numbers – just variable names):
Exercise
Write a script to add up the following figures: 198, 134, 76. Use a print statement to output your answer.
Exercise
Write a script to add up the following two numbers: 15, 45. Then subtract the answer from 100. Use a print statement to output your answer.
Exercise
Use variables to calculate the answer to the following sum:
(200 * 15) / 10
Use a print statement to output your answer.
In the next part of these PHP tutorials, we'll take a look at Conditional Logic.
$first_number = 1.2;
$second_number = 2.5;
$sum_total = $second_number + $first_number;
print ($sum_total);
?>
You add up, subtract, divide and multiply these numbers in exactly the same way as the integers you've been using. A warning comes with floating point numbers, though: you shouldn't trust them, if you're after a really, really precise answer!
Some Exercises
To round up this section on number variables, here's a few exercises (In your print statements, there should be no numbers – just variable names):
Exercise
Write a script to add up the following figures: 198, 134, 76. Use a print statement to output your answer.
Exercise
Write a script to add up the following two numbers: 15, 45. Then subtract the answer from 100. Use a print statement to output your answer.
Exercise
Use variables to calculate the answer to the following sum:
(200 * 15) / 10
Use a print statement to output your answer.
In the next part of these PHP tutorials, we'll take a look at Conditional Logic.
PHP and Division
To divide one number by another, the / symbol is used in PHP. If you see 20 / 10, it means divide 10 into 20. Try it yourself:
$first_number = 10;
$second_number = 20;
$sum_total = $second_number / $first_number;
print ($sum_total);
?>
Again, you have to be careful of operator precedence. Try this code:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number / $first_number;
print ($sum_total);
?>
PHP won't work out the sum from left to right! Division is done before subtraction. So this will get done first:
$second_number / $first_number
And NOT this:
$third_number - $second_number
Using parentheses will clear things up. Here's the two versions for you to try:
Version one
$sum_total = $third_number - ($second_number / $first_number);
Version two
$sum_total = ($third_number - $second_number) / $first_number;
The first version will get you an answer of 98, but the second version gets you an answer of 8! So remember this: division and multiplication get done BEFORE subtraction and addition. Use parentheses if you want to force PHP to calculate a different way.
In the next part, we'll take a look at how PHP handles floating point numbers.
$first_number = 10;
$second_number = 20;
$sum_total = $second_number / $first_number;
print ($sum_total);
?>
Again, you have to be careful of operator precedence. Try this code:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number / $first_number;
print ($sum_total);
?>
PHP won't work out the sum from left to right! Division is done before subtraction. So this will get done first:
$second_number / $first_number
And NOT this:
$third_number - $second_number
Using parentheses will clear things up. Here's the two versions for you to try:
Version one
$sum_total = $third_number - ($second_number / $first_number);
Version two
$sum_total = ($third_number - $second_number) / $first_number;
The first version will get you an answer of 98, but the second version gets you an answer of 8! So remember this: division and multiplication get done BEFORE subtraction and addition. Use parentheses if you want to force PHP to calculate a different way.
In the next part, we'll take a look at how PHP handles floating point numbers.
PHP and Multiplication
To multiply in PHP (and just about every other programming language), the * symbol is used. If you see 20 * 10, it means multiply 20 by 10. Here's some code for you to try:
$first_number = 10;
$second_number = 20;
$sum_total = $second_number * $first_number;
print ($sum_total);
?>
In the above code, we're just multiplying whatever is inside of our two variables. We're then assigning the answer to the variable on the left of the equals sign. (You can probably guess what the answer is without running the code!)
Just like addition and subtraction, you can multiply more than two numbers:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number * $second_number * $first_number;
print ($sum_total);
?>
And you can even do this:
$sum_total = $third_number * $second_number * 10;
But try this code. See if you can guess what the answer is before trying it out:
$first_number = 10;
$second_number = 2;
$third_number = 3;
$sum_total = $third_number + $second_number * $first_number;
print ($sum_total);
?>
What answer did you expect? If you were expecting to get an answer of 50 then you really need to know about operator precedence! As was mentioned, some operators (Math symbols) are calculated before others in PHP. Multiplication and division are thought to be more important that addition and division. So these will get calculated first. In our sum above, PHP sees the * symbol, and then multiplies these two numbers first. When it works out the answer, it will move on to the other symbol, the plus sign. It does this first:
$second_number * $first_number;
Then it moves on to the addition. It doesn't do this first:
$third_number + $second_number
This makes the parentheses more important than ever! Use them to force PHP to work out the sums your way. Here's the two different version. Try them both:
Version one
$sum_total = $third_number + ($second_number * $first_number);
Version two
$sum_total = ($third_number + $second_number) * $first_number;
Here's we're using parentheses to force two different answers. PHP will work out the sum between the parentheses first, and then move on to the other operator. In version one, we're using parentheses to make sure that PHP does the multiplication first. When it gets the answer to the multiplication, THEN the addition is done. In version two, we're using parentheses to make sure that PHP does the addition first. When it gets the answer to the addition, THEN the multiplication is done.
In the next part, we'll take a look at division.
$first_number = 10;
$second_number = 20;
$sum_total = $second_number * $first_number;
print ($sum_total);
?>
In the above code, we're just multiplying whatever is inside of our two variables. We're then assigning the answer to the variable on the left of the equals sign. (You can probably guess what the answer is without running the code!)
Just like addition and subtraction, you can multiply more than two numbers:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number * $second_number * $first_number;
print ($sum_total);
?>
And you can even do this:
$sum_total = $third_number * $second_number * 10;
But try this code. See if you can guess what the answer is before trying it out:
$first_number = 10;
$second_number = 2;
$third_number = 3;
$sum_total = $third_number + $second_number * $first_number;
print ($sum_total);
?>
What answer did you expect? If you were expecting to get an answer of 50 then you really need to know about operator precedence! As was mentioned, some operators (Math symbols) are calculated before others in PHP. Multiplication and division are thought to be more important that addition and division. So these will get calculated first. In our sum above, PHP sees the * symbol, and then multiplies these two numbers first. When it works out the answer, it will move on to the other symbol, the plus sign. It does this first:
$second_number * $first_number;
Then it moves on to the addition. It doesn't do this first:
$third_number + $second_number
This makes the parentheses more important than ever! Use them to force PHP to work out the sums your way. Here's the two different version. Try them both:
Version one
$sum_total = $third_number + ($second_number * $first_number);
Version two
$sum_total = ($third_number + $second_number) * $first_number;
Here's we're using parentheses to force two different answers. PHP will work out the sum between the parentheses first, and then move on to the other operator. In version one, we're using parentheses to make sure that PHP does the multiplication first. When it gets the answer to the multiplication, THEN the addition is done. In version two, we're using parentheses to make sure that PHP does the addition first. When it gets the answer to the addition, THEN the multiplication is done.
In the next part, we'll take a look at division.
How to Subtract in PHP
We're not going to weigh things down by subjecting you to torrents of heavy Math! But you do need to know how to use the basic operators. First up is subtracting.
To add up using PHP variables, you did this:
$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;
print ($sum_total);
?>
Subtraction is more or less the same. Instead of the plus sign (+), simply use the minus sign (-). Change your $sum_total line to this, and run your code:
$sum_total = $second_number - $first_number;
The s$sum_total line is more or less the same as the first one. Except we're now using the minus sign instead (and reversing the two variables). When you run the script you should, of course, get the answer 10. Again, PHP knows what is inside of the variables called $second_number and $first_number. It knows this because you assigned values to these variables in the first two lines. When PHP comes across the minus sign, it does the subtraction for you, and puts the answer into the variable on the left of the equals sign. We then use a print statement to display what is inside of the variable.
Just like addition, you can subtract more than one number at a time. Try this:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number - $first_number;
print ($sum_total);
?>
The answer you should get is 70. You can also mix addition with subtraction. Here's an example:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number + $first_number;
print ($sum_total);
?>
Run the code above. What answer did you get? Was it the answer you were expecting? Why do you think it printed the number it did? If you thought it might have printed a different answer to the one you got, the reason might be the way we set out the sum. Did we mean 100 - 20, and then add the 10? Or did we mean add up 10 and 20, then take it away from 100? The first sum would get 90, but the second sum would get 70.
To clarify what you mean, you can use parentheses in your sums. Here's the two different versions of the sum. Try them both in your code. But note where the parentheses are:
Version one
$sum_total = ($third_number - $second_number) + $first_number;
Version two
$sum_total = $third_number - ($second_number + $first_number);
It's always a good idea to use parentheses in your sums, just to clarify what you want PHP to calculate. That way, you won't get a peculiar answer!
Another reason to use parentheses is because of something called operator precedence. In PHP, some operators (Math symbols) are calculated before others. This means that you'll get answers that are entirely unexpected! As we'll find out right now in the next part - Multiplication.
To add up using PHP variables, you did this:
$first_number = 10;
$second_number = 20;
$sum_total = $first_number + $second_number;
print ($sum_total);
?>
Subtraction is more or less the same. Instead of the plus sign (+), simply use the minus sign (-). Change your $sum_total line to this, and run your code:
$sum_total = $second_number - $first_number;
The s$sum_total line is more or less the same as the first one. Except we're now using the minus sign instead (and reversing the two variables). When you run the script you should, of course, get the answer 10. Again, PHP knows what is inside of the variables called $second_number and $first_number. It knows this because you assigned values to these variables in the first two lines. When PHP comes across the minus sign, it does the subtraction for you, and puts the answer into the variable on the left of the equals sign. We then use a print statement to display what is inside of the variable.
Just like addition, you can subtract more than one number at a time. Try this:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number - $first_number;
print ($sum_total);
?>
The answer you should get is 70. You can also mix addition with subtraction. Here's an example:
$first_number = 10;
$second_number = 20;
$third_number = 100;
$sum_total = $third_number - $second_number + $first_number;
print ($sum_total);
?>
Run the code above. What answer did you get? Was it the answer you were expecting? Why do you think it printed the number it did? If you thought it might have printed a different answer to the one you got, the reason might be the way we set out the sum. Did we mean 100 - 20, and then add the 10? Or did we mean add up 10 and 20, then take it away from 100? The first sum would get 90, but the second sum would get 70.
To clarify what you mean, you can use parentheses in your sums. Here's the two different versions of the sum. Try them both in your code. But note where the parentheses are:
Version one
$sum_total = ($third_number - $second_number) + $first_number;
Version two
$sum_total = $third_number - ($second_number + $first_number);
It's always a good idea to use parentheses in your sums, just to clarify what you want PHP to calculate. That way, you won't get a peculiar answer!
Another reason to use parentheses is because of something called operator precedence. In PHP, some operators (Math symbols) are calculated before others. This means that you'll get answers that are entirely unexpected! As we'll find out right now in the next part - Multiplication.
Concatenate
You can join together direct text, and whatever is in your variable. The full stop (period or dot, to some) is used for this. Suppose you want to print out the following "My variable contains the value of 10". In PHP, you can do it like this:
$first_number = 10;
$direct_text = 'My variable contains the value of ';
print ($direct_text . $first_number);
?>
So now we have two variables. The new variable holds our direct text. When we're printing the contents of both variables, a full stop is used to separate the two. Try out the above script, and see what happens. Now delete the dot and then try the code again. Any errors?
You can also do this sort of thing:
$first_number = 10;
print ('My variable contains the value of ' . $first_number);
?>
This time, the direct text is not inside a variable, but just included in the Print statement. Again a full stop is used to separate the direct text from the variable name. What you've just done is called concatenation. Try the new script and see what happens.
$first_number = 10;
$direct_text = 'My variable contains the value of ';
print ($direct_text . $first_number);
?>
So now we have two variables. The new variable holds our direct text. When we're printing the contents of both variables, a full stop is used to separate the two. Try out the above script, and see what happens. Now delete the dot and then try the code again. Any errors?
You can also do this sort of thing:
$first_number = 10;
print ('My variable contains the value of ' . $first_number);
?>
This time, the direct text is not inside a variable, but just included in the Print statement. Again a full stop is used to separate the direct text from the variable name. What you've just done is called concatenation. Try the new script and see what happens.
More Variable Practice
In the previous section, you started to work with variables. You outputted text to a page. In the next few sections, you'll do some more work with variables, and learn how to do your sums with PHP.
But now that you can print text to a page, let's try some numbers. Start with the basic PHP page again, and save your work as variables2.php:
More on Variables
print ("Basic Page");
?>
We'll now set up a variable and print it to the page. So change your code to this:
$first_number = 10;
print ($first_number);
?>
All the code does is to print the contents of the variable that we've called $first_number. Remember: if you're printing direct text then you need quotation marks; if you're printing a variable name then you leave the quotes out. To see why, run the first script above. Then change the print line to this:
print ("$first_number");
In other words, add double quotation marks around your variable name. Did it make a difference? What did you expect would print out? Now change the double quotes to single quotes. Run your script again. With double quotes, the number 10 still prints; with single quotes, you get the variable name!
TIP: We recommend you use single quotes for your direct text, and NOT double quotes - there's fewer hassles if you do!
But now that you can print text to a page, let's try some numbers. Start with the basic PHP page again, and save your work as variables2.php:
print ("Basic Page");
?>
We'll now set up a variable and print it to the page. So change your code to this:
$first_number = 10;
print ($first_number);
?>
All the code does is to print the contents of the variable that we've called $first_number. Remember: if you're printing direct text then you need quotation marks; if you're printing a variable name then you leave the quotes out. To see why, run the first script above. Then change the print line to this:
print ("$first_number");
In other words, add double quotation marks around your variable name. Did it make a difference? What did you expect would print out? Now change the double quotes to single quotes. Run your script again. With double quotes, the number 10 still prints; with single quotes, you get the variable name!
TIP: We recommend you use single quotes for your direct text, and NOT double quotes - there's fewer hassles if you do!
Subscribe to:
Posts (Atom)