Conditional Statements
PHP allows you to choose what action to take based on the result of a condition. This condition can be anything you choose, and you can combine conditions to make actions that are more complicated. Here is a working example:
<?php
$Age = 20;
if ($Age < 18) {
print "You're young - enjoy it!\n";
} else {
print "You're not under 18\n";
}
if ($Age >= 18 && $Age < 50) {
print "You're in the prime of your life\n";
} else {
print "You're not in the prime of your life\n";
}
if ($Age >= 50) {
print "You can retire soon - hurrah!\n";
} else {
print "You cannot retire soon :( ";
}
?>At the most basic level, PHP evaluates if statements left to right, meaning that it first checks whether $Age is greater or equal to 18, then checks whether $Age is less than 50. The double ampersand, &&, means that both statements must be true if the print "You're in the prime of your life\n" code is to be executed—if either one of the statements is not true for some reason, "You're not in the prime of your life" is printed out instead. The order in which conditions are checked varies when operator precedence matters; this is covered in the next chapter.
As well as &&, there is also || (the pipe symbol printed twice) which means OR. In this situation, the entire statement is evaluated as true if any of the conditions being checked is true.
There are several ways to compare two numbers. We have just looked at < (less than), <= (less than or equal to), and >= (greater than or equal to). We will ...