|In the last tutorial we discussed the if statement and the else clause and how it can be used to allow your program to make simple either/or decisions. In this tutorial, we will examine how to add the elseif clause to the if statement to allow your program to make more complex decisions.|
Ok, we all know that the world is more complicated than just either/or situations and therefore you will want your program to be able to make more complicated decisions. It is possible to code your program to perform a different task depending on which of a number of tests (expressions) is true. The program will test each expression in a linear sequence until one of the expressions is found to be true. Then the program will complete the rest of the code that corresponds to that expression. If your program gets to the end of the sequence of code and none of the tested expressions are true the default else clause will be performed. This default else clause is optional. You might want the program to do nothing if it does not find one of the expressions to be true. In that case, you have the option to omit the default code. Let's take a look at a real-life example.
In our example you have a business website. You also have a different product for sale at a super discounted price each month. In the upper left corner of the front page of your website you want to display an image of the current specially priced product. Because this product changes each month, you will want your program to get the current month and set the corresponding image for the current month. The first three lines of code follow.
The first line of code initialized the variable $current_image to null. The second line of code gets the current month as a numerical value between 1 and 12. The third line of code test for the first expression -- Is the current month January (1). If this expression is true, the $current_image variable will be set to image_jan.jpg.
I bet you can guess how the rest of the code will work. We will use the elseif clause to test the other expressions.