PHP If, Else & Else-If Statement
ADVERTISEMENTS
If Statement
If statement is a condition statement, which is used for checking only one condition at a time, It can be true or false at a time.
Syntax of the If statement
if (condition) {
Condition true, execute statement;
}
Condition true, execute statement;
}
Understand If statement from this example :
<?php
$m = 5;
if ($m < 10)
{
$n = "hello program";
echo $n;
}
?>
Output:
hello program
Else Statement
Else is a condition statement, It is used with If statement for checking only two conditions, It happens when if the condition goes to a false condition.
Syntax of the Else statement
if (condition) {
Condition true, execute statement : 1;
} else {
execute statement : 2;
}
Condition true, execute statement : 1;
} else {
execute statement : 2;
}
Understand Else statement from this example :
<?php
$m = 5;
if ($m > 5)
{
$n = "hello program";
echo $n;
}
else
{
$n = "bye program";
echo $n;
}
?>
Output:
bye program
Else If Statement
ElseIf is a condition statement, It is used with If statement for checking more than two conditions.
Syntax of the Else If statement
if (condition 1) {
condition 1 true, execute statement : 1;
} else if (condition 2) {
condition 2 true, execute statement : 2;
}
:
:
} else if (condition n) {
condition n true, execute statement: n;
} else {
execute the default statement;
}
condition 1 true, execute statement : 1;
} else if (condition 2) {
condition 2 true, execute statement : 2;
}
:
:
} else if (condition n) {
condition n true, execute statement: n;
} else {
execute the default statement;
}
Understand the Else If the statement from this example :
<?php
$m = 5;
if ($m == 1)
{
echo "Hello";
}
else if ($m == 5)
{
echo "Good job";
}
else
{
echo "Have a nice day";
}
?>
Output:
Good job