PHP Chapter 3 (Conditional Logic)

PHP If Statements

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:
<IMG SRC =church.jpg>
Just plain HTML. But you can put that code inside of the print statement:
print ("<IMG SRC =images/church.jpg>");
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. (Gohere to get the course files, if you haven't already.)
Copy the images folder to your www (root) directory. Then try the following script:
<?PHP
print ("<IMG SRC =images/church.jpg>");
?>
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.

Some Practise with PHP If Statements

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 another image (the kitten image, which is also in your images folder). Here's some code:
<?PHP
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
?>
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 ("<IMG SRC =images/kitten.jpg>");
}
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 ("<IMG SRC = images/kitten.jpg>"); }
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:
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
if ($church_image == 1) {
print ("<IMG SRC =images/church.jpg>");
}
?>
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 ("<IMG SRC =images/church.jpg>");

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:
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else {
print ("<IMG SRC =images/church.jpg>");
}
?>
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 ("<IMG SRC =images/church.jpg>");
}
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?

PHP if ... else if Statements

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:
<?PHP
$kitten_image = 1;
$church_image = 0;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else if ($church_image == 1) {
print ("<IMG SRC =images/church.jpg>");
}
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 ("<IMG SRC =images/church.jpg>");
}
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 youdownloaded. 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!

PHP Comparison Operators

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.
PHP Comparison Operators
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) {
}
!= (Is NOT 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 ( >= )

PHP 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:
<?PHP
$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?

PHP Less Than, Greater Than

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.
<?PHP
$total_spent = 110;
$discount_total = 100;
if ($total_spent > $discount_total) {
print("10 percent discount applies to this order!");
}
?>
By using the Greater 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):
<?PHP
$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.

Less Than or Equal To, Greater Than or Equal To

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 theLess 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.

PHP Switch Statements

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 … ifstatements 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:
<?php
$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.

PHP 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.
PHP Logic Operators
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!

PHP Booleans

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:
<?php
$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!

PHP Operator Precedence

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:
PHP Operator Precedence List
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.

Comments