The opportunity this time, let’s discuss about the conditions in PHP. Contingent explanations are utilized to perform various activities dependent on various conditions.
PHP Conditional Statements
All the time when you compose code, you need to perform various activities for various conditions. You can utilize restrictive articulations in your code to do this.
In PHP we have the accompanying contingent articulations:
- if statement – executes some code if one condition is true
- if…else statement – executes some code if a condition is true and another code if that condition is false
- if…elseif…else statement – executes different codes for more than two conditions
- switch statement – selects one of many blocks of code to be executed
The if statement executes some code if one condition is true.
See the example below. Output “Have a good day!” if the current time (HOUR) is less than 20:
1 2 3 4 5 6 |
<?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } ?> |
The If Else Statements
The if…else statement executes some code if a condition is true and another code if that condition is false.
See the example below. Output “Have a good day!” if the current time is less than 20, and “Have a good night!” otherwise:
1 2 3 4 5 6 7 8 |
<?php $t = date("H"); if ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> |
The If… Else If… Else Statements
The if…elseif…else statement executes different codes for more than two conditions.
See the example below. Output “Have a good morning!” if the current time is less than 10, and “Have a good day!” if the current time is less than 20. Otherwise it will output “Have a good night!”:
1 2 3 4 5 6 7 8 9 10 |
<?php $t = date("H"); if ($t < "10") { echo "Have a good morning!"; } elseif ($t < "20") { echo "Have a good day!"; } else { echo "Have a good night!"; } ?> |