If
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 some thing;
If the condition is not true, then ignore it and do something else(ex. throw exception);
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 $city to NYC (line 3). Then we say "if city is NYC, then print 'I love NYC!'"
<?php
$city = "NYC"; //string assignment ..see quotes
if ($city == "NYC") { //comparison operator
print ("I love NYC!");
}
?>
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
}
Example
<?php
$city = "Chicago";
if ($city == "NYC") {
print ("I love NYC!");
} else {
print ("You don't love NYC??!");
}
?>
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;
<?php
$city = "LA";
if ($city == "NYC") {
print ("I love NYC!");
} elseif ($city == "LA") {
print ("LA..Hollywood!");
}
?>