We can make simple Decisions with the if Statement.
The basic form of an if construct is as follows:
if ( expression ) {
// Run this code
}
// More code here
If you only have one statement of code to execute, you can do without the braces entirely. It's a readability issue.
So, these two code chunks are the same:
if ($banned) { print "You are banned!"; } if ($banned) print "You are banned!";
If the expression inside the parentheses evaluates to true, the code between the braces is run.
If the expression evaluates to false, the code between the braces is skipped.
Here is a working example for if statement:
<?php $Age = 20; if ($Age < 18) { print "under 18\n"; } else { print "You're not under 18\n"; } ?>
The code above generates the following result.
Here's another example that uses the >= (greater than or equal) and <= (less than or equal) comparison operators, as well as the && (and) logical operator:
<?PHP $myValue = 23; if ( $myValue >= 10 && $myValue <= 20 ) { echo "between 10 and 20."; } ?>
Here's the previous example rewritten to use an if statement inside another if statement:
<?PHP $myValue = 23; if ( $myValue >= 10 ) { if ( $myValue <= 20 ) { echo "10 and 20."; } } ?>
We can providing an alternative choice with the else statement.
The PHP if else statement has the following syntax.
if(condition_0){ ... }else{ ... }
or
if(condition_0){ ... }elseif (condition_1){ }elseif (condition_2){ }else{ ... }
else
statement lets you run one block of code
if an expression is true, and a different block of code if the expression is false.
<?PHP $myValue = 23; if ( $myValue >= 10 ) { echo "greater than 10."; } else { echo "Less than 10!"; } ?>
The code above generates the following result.
You can even combine the else statement with another if statement to make as many alternative choices as you like:
<?php $Age = 23; if ($Age < 10) { print "You're under 10"; } elseif ($Age < 20) { print "You're under 20"; } elseif ($Age < 30) { print "You're under 30"; } elseif ($Age < 40) { print "You're under 40"; } else { print "You're over 40"; } ?>
The code above generates the following result.
The following code shows how to use if-elseif-else statement.
<?php $name = "Jack"; if($name == "") { print("You have no name."); } elseif(($name == "leon") OR ($name == "Leon")) { print("Hello, Leon!"); } else { print("Your name is '$name'."); } ?>
The code above generates the following result.