The PHP If Statement And The Elseif Clause

The PHP If Statement And The Elseif Clause
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.

if statement with else clause

if ( $current_month > 10 )
{ echo "Welcome and Merry Christmas"; }
else { echo "Sorry, we are closed until November 1st"; }

elseif clause

if (expression 1 is true) { perform this code }
elseif (expression 2 is true) { perform this code instead }
else { perform this default code if no expression is true }

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.

$current_image = "";
$current_month = date(n);

if ($current_month == 1)
{ $current_image = "image_jan.jpg"; }

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.

Next →






This site needs an editor - click to learn more!



RSS
Editor's Picks Articles
Top Ten Articles
Previous Features
Site Map





Content copyright © 2023 by Diane Cipollo. All rights reserved.
This content was written by Diane Cipollo. If you wish to use this content in any manner, you need written permission. Contact BellaOnline Administration for details.