Monday, January 7, 2008

if … else Statements in PHP


$kitten_image = 0;
$church_image = 1;

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

?>

Copy this new script, save your work, and try it out. You should find that the church image displays in the browser. This time, an if … else statement is being used. Let’s see how it works.

The syntax for the if else statement is this:

if (condition_to_test) {

}
else {

}

If you look at it closely, you’ll see that you have a normal If Statement first, followed by an “else” part after it. Here’s the “else” part:

else {

}

Again, the left and right curly brackets are used. In between the curly brackets, you type the code you want to execute. In our code, we set up two variables:

$kitten_image = 0;
$church_image = 1;

The variable called $kitten_image has been assigned a value of 0, and the variable called $church_image has been assigned a value of 1. The first line of the if statement tests to see what is inside of the variable called $kitten_image. It’s testing to see whether this variable has a value of 1.

if ($kitten_image == 1) {

What we’re asking is: “Is it true that $kitten_image holds a value of 1?” The variable $kitten_image holds a value of 0, so PHP sees this as not true. Because a value of “not true” has been returned (false, if you like), PHP ignores the line of code for the if statement. Instead, it will execute the code for the “else” part. It doesn’t need to do any testing – else means “when all other options have been exhausted, run the code between the else curly brackets.“ For us, that was this:

else {
print ("");
}

So the church image gets displayed. Change your two variables from this:

$kitten_image = 0;
$church_image = 1;

To this:

$kitten_image = 1;
$church_image = 0;

No comments: