When the program has conditions then statements are used.
the condition means when we want to do something when something will happen, for example, there is a situation where we want to add number when number if even.'
to apply these kinds of situations in a program conditional statements are used.
There are the following types of statements.
- if statement
- if-else statement
- if-else if statement
- nested if statement
- switch statement
- conditional operator statement
if statement
when the program has only one condition and related statement then if statement is used.
<?php
$n=10;
if($n%2 == 0){
echo "Even number";
}
?>
if-else statement
<?php
$n=11;
if($n%2==0){
echo "Even number";
}
else{
echo "Odd number";
}
?>
if-else-if statement
<?php
$marks=90;
if($marks > 90){
echo "Grade A";
}
else if($marks>80){
echo "Grade B";
}
else if($marks>70){
echo "Grade C";
}
else{
echo "Grade D";
}
?>
Nested if statement
when the program has a condition within other condition, there we use nested if statement.
<?php
$a=100;
$b=200;
$c=300;
if($a > $b){
if($a > $c){
echo "A is greater.";
}
else{
echo "C is greater.";
}
}
else if($b > $a){
if($b > $c){
echo "B is greater.";
}
else{
echo "C is greater.";
}
}
?>
Switch Statement
It is an alternative statement of if-else if statement there is little difference is that relational, logical operators can not be used here.
<?php
$day=6;
switch($day){
case '1':
echo "Sunday";
break;
case '2':
echo "Monday";
break;
case '3':
echo "Tuesday";
break;
case '4':
echo "Wednesday";
break;
case '5':
echo "Tuesday";
break;
case '6':
echo "Friday";
break;
case '7':
echo "Saturday";
break;
default :
echo "Invalid number";
}
?>
Conditional operators
It is an alternative to the if-else statement, and it is an inline conditional statement.
<?php
$n=100;
$n%2 == 0 ? echo "Even number": echo "Odd number";
?>