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 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!