Iffy If Statements
Posted on 25. Feb, 2010 by admin in Basics
For the next four tutorials we will be dealing with something called conditionals. No it is not something you wash your hair with… The definition of a conditional is “a statement that depends on a condition being true or false.” To help you understand stand this lets start out with an code example:
<?php
//Color of Stoplight
$stopLight = "Green";
//If statement
if($stopLight == "Red") {
echo "Stop!";
}
elseif($stopLight == "Yellow") {
echo "Slow down...";
}
elseif($stopLight == "Green") {
echo "Floor it!";
}
else {
echo "The stoplight must be broken.";
}
?>
Output:
Floor it!
Lets break this down part by part. We are using a “function” called if, but instead of an argument we have a conditional in-between the parentheses.
The first if statement says, if $stopLight is equal to “Red” then it will run the code in the {} which prints out “Stop!” This is not true so it will not run the code. Instead, the function will go on to the next statement.
Each successive elseif statement is run if the previous elseif statement was false. If any of statements are true, it will run the code in the {} and skip down to the end } of the else statement.
The else statement is the code that runs if none of the statements are true. For example, if you put “Purple” as the stop light color it would run the code in-between the {} and print “The stoplight must be broken.”
Also when comparing numbers you can replace == with the following to find if numbers or greater than, less than, etc to each other:
- == is equal to
- != is not equal
- <> is not equal
- > is greater than
- < is less than
- >= is greater than or equal to
- <= is less than or equal to
Note: You may use as many if statements as you would like, but elseif and else statements must be accompanied by an if statement before it.

