Page 8
Operators; If, Else, Elseif; Loops
The whole deal about making dynamic websites is that you want your Web
page to be as smart as possible to have code sitting there that can make
all sorts of decisions based on different kinds of user input, user conditions
(what browser is Visitor X using?), or information that you set yourself.
Examples of this could be:
- After a user enters an email address, check that it has a valid form
(whoever@wherever.com) and if not, serve a page that says, "hey pal,
how about a VALID email address?"
- Serve one set of HTML to .com domains and another to .gov domains (where
you try not to use any big words that might confuse 'em).
- Know whether a customer at your online store is meeting a minimum dollar
amount for an online credit card purchase.
- And on and on and on the possibilities are limitless.
If
The way to make your pages smart is to use If, Else, and Elseif statements
along with Comparison and Logical Operators. The most important one of these
is the if statement, which gives you the ability to code:
If some condition
is true, then do somesuch thing;
If the condition is not true, then ignore it;
The syntax of this statement is as follows:
if (condition) {
// code in here to execute if the condition is true
}
Here it is in action. First we set the variable $FavoriteColor to blue
(line 3). Then we say "if FavoriteColor is blue, then print 'I like
blue too!'"
<?php
$FavoriteColor = "blue";
if ($FavoriteColor == "blue") {
print ("I like blue too!");
}
?>
Else
Else builds on the if statement as if to say:
If some condition
is true, then do somesuch thing;
ELSE, in case that first condition is NOT true, then do this other thing.
It works like this:
if (condition) {
// code in here to execute if the condition is true
} else {
// code in here to execute if the condition is not true
}
Here it is in motion:
<?php
$FavoriteColor = "yellow";
if ($FavoriteColor == "blue") {
print ("I like blue too!");
} else {
print ("You don't like blue?! Crazy fool!");
}
?>
What you see above is the typical format for writing statements like this.
The key part is to see where the curly braces are so you don't get confused
as to which statement belongs to which piece of the code. Above, the first
set of { and } belong to the "if," the second { and } belong to
the "else."
Elseif
There's one more sibling in the if, else family, and it's called
elseif. Where elseis sort of a blanket control that make
something happen as long as the if statement is not true, elseif
makes something happen if a specific condition is met:
IF some condition
is true, then do somesuch thing;
ELSEIF some other specific condition is true, then do another thing;
It looks like this:
<?php
$FavoriteColor = "green";
if ($FavoriteColor == "blue") {
print ("I like blue too!");
} elseif ($FavoriteColor = green) {
print ("MMMmmmmmmmmmm, green!");
}
?>
You could even add an ELSE statement at the end in case FavoriteColor were
neither blue nor green.
next page»
|