Introduction to Conditional Statements in PHP

Estudies4you

Conditional Statements – Introduction

PHP has conditional statements like any other programming language. Conditional statements allowed in PHP are:
➤if
➤if-else
➤if-else if
➤switch

Syntax: if
<?php
if(condition)
{
statement;
}
?>
                                  
Example:
If the condition satisfies, the echo statement will be printed.
<?php
$t = 70;
if($t==70)
{
echo "if condition is executed";
}
?>


if-else Statement
Syntax: if-else Example
<?php
if(condition)
statement to be executed;
}
else
{
statement to be executed";
}
?>

Example:
<?php
$p=60;
if ($p<"60")
{
echo "if condition is satisfied";
}
else
{
echo "if condition is not satisfied";
}
?>

if-else if Statement
Syntax: if-else if Example
<?php
if(conditionl)
Statement(s) to be executed;
else if(condition2)
{
Statement(s) to be executed;
}
…….
else if(conditionN)
{
Statement(s) to be executed;
}
else
{
Statement(s) to be executed;
}

Example:
<?php
$p=40;
if($p>"40")
{
echo "given value is greater than 40";
}
else if($p<"40")
{
echo "given value is less than 40";
}
else
{
echo "given value is equal to 40";
}
?> 

Switch Statement
Syntax: switch
switch(n)
{
case 1:
Statement to be executed if n=1;
break;
case 2:
Statement to be executed if n=2;
break;
default:
Statement to be executed if n is other than case 1 & 2;
break;
}

Example:
<?php
$numb="9"
switch($numb)
{
case ”7”:
echo "7 is a prime number";
break;
case ”8”:
echo "8 is not a prime number";
break;
case ”9“:
echo "square value of 3";
break;
default:
echo "number entered is invalid";
break; 




To Top