Friday, 1 July 2016

if ... else Statements in PHP

Instead of using two if statements, as in the previous lesson, we can use an if ... else statement. Like this:
<?PHP
$kitten_image = 0;
$church_image = 1;
if ($kitten_image == 1) {
print ("<IMG SRC =images/kitten.jpg>");
}
else {
print ("<IMG SRC =images/church.jpg>");
}
?>
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 ("<IMG SRC =images/church.jpg>");
}
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;
Run your code again and watch what happens. You should see the kitten! But can you work out why?

No comments:

Post a Comment