saftutorials.com
PHP if else if Tutorial

You can decide that which part of code want to execute and which part don't by using if and else...if...else statement. You can use this conditional statement for your decision.


if statement (Execute the part of code when the condition will be true)

if else statement (Execute if condition part of code when the condition will be true otherwise else part of the code will be executed)

if..elseif..else statement (Execute some part of code for more than two conditions)


Syntax and Example for if statement

if(condition){

// This part of code will be executed if condition will be true

}


<!DOCTYPE html>
<html>
<body>
<?php
$a = 7;
$b = 5;
if($a > $b) {
?>
<p>if part execute when condition true : <?php echo $a . ' is greater than ' .$b;?></p>
<?php
}
?>
</body>
</html>

The above code produces the following results

Outputs: if part execute when condition will be true: 7 is greater than 5



Syntax and Example for if else statement

if(condition){

// This part of code will be executed if condition will be true

} else {

// This part of code will be executed if condition will be false

}

<!DOCTYPE html>
<html>
<body>
<?php
$a = 7;
$b = 5;
if($a < $b) {
?>
<p>if part execute when condition will be true : <?php echo $a . ' is greater than ' .$b;?></p>
<?php
} else {
?>
<p>else part execute when condition will be false : <?php echo $b . ' is less than ' .$a;?></p>
<?php
}
?>
</body>
</html>


The above code produces the following results

Outputs: else part execute when condition will be false: 5 is less than 7



Syntax and Example for if elseif else statement


if(condition){

// This part of code will be executed when condition will be true

}else if(condition){

// This part of code will be executed when condition will be true

} else {

// This part of code will be executed when both above conditions will be false

}

<!DOCTYPE html>
<html>
<body>
<?php
$a = 7;
$b = 5;
if($a < $b) {
?>
<p>This part execute when condition will be true : <?php echo $a . ' is greater than ' .$b;?></p>
<?php 
} else if($b < $a){
?>
<p>This part execute when condition will be true : <?php echo $b . ' is less than ' .$a;?></p>
<?php
} else {
?>
<p>This part execute when both condition will be false : <?php echo $b . ' is not less nor greater ' .$a;?></p>
<?php
}
?>
</body>
</html>


The above code produces the following results

Outputs: This part execute when condition will be true: 5 is less than 7


Find us on

Facebook Google Plus Twitter Pinterest YouTube

web statistic