The if construct allows for conditional execution of code fragments.
It has several statements:
The if statement
The if...else statement
The if...elseif statement
The if...elseif....else statement
if statementif structure:
if (expr)
statement
// statement group
if (expr){
statement1
statement2
}
the expr is the condition.
<?php if ($a > $b) echo "a is bigger than b"; ?>
<?php
$month = 1;
if ($month == 1) {
echo "The month is ".$month;
$days = 31;
}
?>
if...else statementthe else extends an if statement to execute a statement in case the expression evaluates to FALSE.
if...else structure:
if (expr){
// statement to be executed when expr evaluates to TRUE.
}
else{
// statement to be executed when expr evaluates to FALSE.
}
<?php
$a = 5;
$b = 7;
if ($a > $b) {
echo "a is greater than b";
} else {
echo "a is NOT greater than b";
}
?>
if...elseif statementelseif is a combination of if and else.
it can also be writed as else if
if...elseif structure:
if (expr1){
// statement to be executed when expr1 evaluates to TRUE.
} else if (expr2){
// statement to be executed when expr1 is FALSE AND expr2 is TRUE.
} else{
// statement to be executed when expr1 and expr2 are both FALSE.
}
<?php
$a = 5;
$b = 7;
if ($a > $b) {
echo "a is bigger than b";
} elseif ($a == $b) {
echo "a is equal to b";
} else {
echo "a is smaller than b";
}
?>
If statements can be nested infinitely within other if statements.
if (expr1){
if (expr2){
if (expr3){
// statement to be executed when expr1,expr2,expr3 are both TRUE.
}
}
else{
// statement to be executed when expr1 is TRUE and expr2 is FALSE.
}
}
else{
// statement to be executed when expr1 evaluates to FALSE.
}
If statement with embedded HTML<?php
$a = 5;
?>
<?php if ($a == 5){ ?>
A is equal to 5
<?php } ?>
If statementIn If statement, We can change the opening brace to a colon: and the closing brace to endif;;
For example:
<?php
$a = 3;
if ($a == 1):
echo "a = 1";
elseif ($a == 2):
echo "a = 2";
else:
echo "a is neither 1 nor 2 ";
endif;
?>