If else conditions are written where the logic is straightforward. There are various ways to use if statement in PHP.
PHP if is used to execute a block of code based on the condition, only if the condition is true.
<?php
if($condition){
// Code Starts here
}
?>
<?php
$no = 7;
if($no > 5)
{
echo "$no is greater than 5";
}
?>
The If-else statement allows to execute different blocks of code based on whether a specified condition is true or false. It is also known as control-flow statements.
<?php
if($codition)
{
// Code to be executed if codition is TRUE
}
else
{
// Code to be executed if condition is FALSE
}
?>
<?php
$no = 6;
if($no > 10)
{
echo "$no is greater than 10";
}
else{
echo "$no is lesser than 10";
}
?>
The If-else-if statement is used to check more than two conditions. So, we can check multiple conditions using this statement.
<?php
if($condition1)
{
// Code to be executed if condition1 is TRUE
}
else if($condition2)
{
// Code to be executed if condition2 is TRUE
}
else if($condition3)
{
// Code to be executed if condition3 is TRUE
}
else
{
// Code to be executed if all conditions are FALSE
}
?>
<?php
$no = 60;
if($no < 10)
{
echo "$no is greater than 10";
}
elseif($no < 25)
{
echo "$no is lesser than 10";
}
elseif($no < 45)
{
echo "$no is lesser than 10";
}
else
{
echo "All conditions are FALSE";
}
?>
A nested if statement is an if statement that is the target of another if statement.
<?php
if($condition1){
// Code to be executed if condition1 is correct
if($condition2){
// Code to be executed if codition1 & condition2 are correct
}
}
?>
<?php
$no = 16;
if($no > 10)
{
echo "$no is greater than 10";
if($no > 20)
{
echo "but $no is not greater than 20";
}
}
?>