Monday, January 7, 2008

if … else if Statements in PHP

else if (another_condition_to_test) {

}

Change your code to this, to see how else if works:


$kitten_image = 1;
$church_image = 0;

if ($kitten_image == 1) {
print ("");
}
else if ($church_image == 1){
print ("");
}
else {
print ("No value of 1 detected");
}

?>

Here’s we’re just testing to see which of our variables holds a value of 1. But notice the “else if” lines (and that there’s a space between else and if):

else if ($church_image == 1){
print ("");
}

What you’re saying is “If the previous if statement isn’t true, then try this one.” PHP will then try to evaluate the new condition. If it’s true (the $church_image variable holds a value of 1), then the code between the new curly brackets gets executes. If it’s false (the $church_image variable does NOT holds a value of 1), then the line of code will be ignored, and PHP will move on.

To catch any other eventualities, we have an “else” part at the end. Notice that all parts (if, else if, and else) are neatly sectioned of with pairs of curly brackets:

if ($kitten_image == 1) {

}

else if ($church_image == 1) {

}

else {

}

You can add as many else if parts as you like, one for each condition that you want to test. But change your two variables from this:

$kitten_image = 1;
$church_image = 0;

to this:

$kitten_image = 0;
$church_image = 0;

No comments: