If-Else Statements
Written by Jen

Knowing how to use the if statement is a necessity in php programming. Imagine you were in a situation where you had to choose between two options. If you chose to go with option one, then you'd get consequence one. Else you'd get consequence 2. Sound simple enough? Well the if statement in PHP works just like that.

As you should've seen in the previous tutorial about operators, comparison operators are often combined with if-else statements. For example:

<?php

$name = 'Jen';

if ($name == 'Jen') {
   echo "Your statement is true";
}
else {
   echo "Your statement is false";
}

?>

And I would get a display that said "Your statement is true". Didn't really understand the script? Basically what I was trying to say was if my name was Jen then I would get a statement saying it was true. But if the name entered wasn't Jen then the statement would be false. But since the name I entered in the $name variable in the beginning was Jen, then the statement would obviously come out as being true.

Of course this could work out to being the complete opposite:

<?php

$name = 'Jen';

if ($name == 'Kathrin') {
   echo "Your statement is true";
}
else {
   echo "Your statement is false";
}

?>

This time I would see a display of "Your statement is false" because the variable did not match the if statement.

Of course this isn't limited to just two options. You can also have 'elseif', which is an extra conditional test within an if statement. It's like doing a second if test for a true or false value. This comes after the first if statement but before the else statement. For example:

<?php

$number = 19;

if ($number > 30) {
   echo "$number is greater than 30";
}
elseif ($number > 20) {
   echo "$number is greater than 20";
}
elseif ($number > 10) {
   echo "$number is greater than 10";
}
else {
   echo "$number is less than 30, 20 and 10";
}

?>

Since 19 is less than 20 and 30 but greater than 10, you would get a display of "19 is greater than 10". If you were to change $number to say 5, the you'd get the statement "5 must be less than 30, 20 and 10". You can have as many elseif statements as you like, provided that they are placed in the correct place in the script.