Conditional Statements in PHP
- Control structure controls the flow of program code’s execution in the application.
- In application program executed sequentially (line by line).
- Control structure allows random execution in code (not sequential).
- It is done under certain conditions.
- It performs different actions which
are based on different conditions.
- PHP provides the following conditional statements:
- If statement (simple) - executes some code if one
condition is true
- If...else statement - executes some code if a
condition is true and another code execute when if the condition is false
(else part execute)
- If...elseif...else statement - executes different codes
for more than two conditions. Else part executes when all if and end if
are false.
- The nested
if...else statements- if...else statements inside an if...else statement the statements
are nested.
- Switch statement - selects one of many
blocks of code to be executed (action code executes according to true
condition block.)
PHP - The If
Statement
The if
the statement executes some code if
one condition is true.
Syntax
if (condition)
{
code to be executed if condition is true;
}
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good
day!";
}
?>
Output:-
Output "Have a good day!" if
the current time (HOUR) is less than 20:
Note:-
date(“H”) show system time.
date(“D”) show system date.
=====================================================================
PHP - The if...else
Statement
The if...else
the statement executes some code if
a condition is true and another code if that condition is false.
Syntax
if (condition) {
code to be executed if condition is true;
}
else {
code to be executed if condition is false;
}
Example
<?php
$t = date("H");
if ($t < "20") {
echo "Have a good
day!";
}
else {
echo "Have a good
night!";
}
?>
output: -
Have a
good night!
Ex.
<?php
if($age < 18)
{ echo 'Child';
// Display Child if age is less than 18 }
else{ echo 'Adult'; // Display Adult if age is
greater than or equal to 18 }
?>
Output:-
Child
======================================================================
PHP - The
if...elseif...else Statement
The if...elseif...else
statement executes different
codes for more than two conditions.
Syntax
if (condition)
{
code to be executed if this condition is true;
}
elseif (condition)
{
code to be executed if first condition is false and this
condition is true;
}
else {
code to be executed if all conditions are false;
}
Example
<?php
$t = date("H");
if ($t < "6") {
echo "Have a good
morning!";
} elseif ($t < ="12") {
echo "hello good
day!";
} else {
echo " good evening!";
}
?>
Output:-
hello
good day!
==============================================================
The
nested if...else statements
When you
find if...else statements inside an if...else
statement the statements are nested. With this statement,
you can get alternative results when a condition is true or false.
0 Comments