Control Structures
Control Structures
STRUCTURES
Conditional Statements
• PHP also allows you to write code that perform different
actions based on the results of a logical or comparative
test conditions at run time.
- The if statement
- The if...else statement
- The if...elseif....else statement
- The switch...case statement
The if Statement
• The if statement is used to execute a block of code only if
the specified condition evaluates to true.
<?php
$d = date("D");
if($d == "Tue"){
echo "It's Tuesday!";
}
?>
The if Statement(contd.)
<?php
$t = date("H");
OUTPUT:
12 is less than 100
The if...else Statement
• The if...else statement allows you to execute one block of
code if the specified condition is evaluates to true and
another block of code if it is evaluates to false.
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} else{
echo "Have a nice day!";
}
?>
The if...else Statement(contd.)
<?php
$t = date("H");
OUTPUT:
13 is odd number
The if...elseif...else Statement
• The if...elseif...else a special statement that is used to combine
multiple if...else statements.
<?php
$d = date("D");
if($d == "Fri"){
echo "Have a nice weekend!";
} elseif($d == "Sun"){
echo "Have a nice Sunday!";
} else{
echo "Have a nice day!";
}
?>
The if...elseif...else Statement(contd.)
<?php
$t = date("H");
<?php
$age = 15;
echo ($age < 18) ? 'Child' : 'Adult';
?>
OUTPUT:
Child
PHP nested if Statement
• The nested if statement contains the if block inside another if block. The inner if statement executes
only when specified condition in outer if statement is true.
<?php
$age = 23;
$nationality = "Indian";
//applying conditions on nationality and age
if ($nationality == "Indian")
{
if ($age >= 18) {
echo "Eligible to give vote";
}
else {
echo "Not eligible to give vote";
}
}
?>
OUTPUT:
Eligible to give vote
PHP switch Statement
• The switch statement is used to perform different actions
based on different conditions.
<?php
$ch = 'c';
switch ($ch)
{
case 'a': OUTPUT:
echo "Choice a";
break;
Choice c
case 'b': Choice d
echo "Choice b"; case a, b, c, and d is not found
break;
case 'c':
echo "Choice c";
echo "</br>";
case 'd':
echo "Choice d";
echo "</br>";
default:
echo "case a, b, c, and d is not found";
}
?>
PHP nested switch statement
<?php
$author = "Stephen King";
$book ="The silence of the lambs";
switch($author)
{
case "JK Rowling":
{
switch($book)
{
case "Harry Potter1";
echo "Harry Potter1, The price is 300$";
break;
case "Harry Potter2";
echo "Harry Potter2, The price is 200$";
break;
OUTPUT:
default:
echo "Author found but not the book"; The silence of the lambs, The
price is 700$
}
}
break;
case "Stephen King":
{
switch($book)
{
case "Hannibal";
echo "Hannibal, The price is 500$";
break;
case "The silence of the lambs";
echo "The silence of the lambs, The price is 700$";
break;
default:
echo "Author found but not the book";
}
}
break;
default:
echo "Author not found";
}
?>