Home and Learn: PHP Programming Course
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");
}
?>
Heres were just testing to see which of our variables holds a value of 1. But notice the else if lines (and that theres a space between else and if):
else if ($church_image == 1) {
print ("<IMG SRC =images/church.jpg>");
}
What youre saying is If the previous if statement isnt true, then try this one. PHP will then try to evaluate the new condition. If its true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If its 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. Its 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.
Dont worry too much about the rest of the code: concentrate on the if statements. All were doing is testing what is inside of the variable called $picture. Were 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, its essential that you have a good grasp of how to use them. To help you along, theres some more about Conditional logic in the next section!
<-- Back One Page | Move on to the Next Part -->
Email us: enquiry at homeandlearn.co.uk