Get latest news and Web Designing tutoria

Friday, 29 May 2015

if ... else Statements in PHP

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?

0 comments:

Post a Comment