HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Conditional statements are used to perform different actions based on different conditions
Very often when you write code, you want to perform different actions for different conditions. You can use conditional statements in your code to do this.
In PHP we have the following conditional statements:
if
statement - executes some code if one condition is trueif...else
statement - executes some code if a condition is true and another code if that condition is falseif...elseif...else
statement - executes different codes for more than two conditionsswitch
statement - selects one of many blocks of code to be executedThe if
statement executes some code if one condition is true.
Syntax
Output "Have a good day!" if the current time (HOUR) is less than 20:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
?>
The if...else
statement executes some code if a condition is true and
another code if that condition is false.
Syntax
Output "Have a good day!" if the current time is less than 20, and "Have a good night!" otherwise:
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good day!";
}
else {
echo
"Have a good night!";
}
?>
The if...elseif...else
statement executes different codes for more than two
conditions.
Syntax
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!":
<?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!";
}
?>
The switch
statement will be explained in the next chapter.
Output "Hello World" if $a
is greater than $b
.
$a = 50; $b = 10; > { echo "Hello World"; }