Microsoft Word - Core PHP Programming Using PHP to Build Dynamic Web Sites

(singke) #1

code in the greater if statement is skipped. That is to say, only one match will be made.
Listing 3.1 demonstrates an if-elseif-else statement.


Of course, you are not obligated to have an elseif or an else. Sometimes you might
want to build a very simple if statement as in Listing 3.2.


You can use if to build a series of checks that covers all possible cases. Just start by
checking for the first condition with an if; then check for each following condition with
an elseif. If you put an else at the end, you will have accounted for all possible cases.
Listing 3.3 uses this method to print the day of the week in German. The script gets
today's name and then compares it to the days Monday through Saturday. If none of these
match, it is assumed to be Sunday.


Listing 3.1 An if-elseif-else Statement


<?
if($name == "")
{
print("You have no name.");
}
elseif(($name == "leon") OR ($name == "Leon"))
{
print("Hello, Leon!");
}
else
{
print("Your name is '$name'.");
}
?>


Listing 3.2 A Simple if Statement


<?
if(date("D") == "Mon")
{
print("Remember to put the trash out.");
}
?>


The? Operator


PHP offers an abbreviated version of the if statement which borrows syntax from C. It
uses the question mark as a tertiary operator. Figure 3-2 outlines the format.


Figure 3-2. The? operator.
Free download pdf