PHP IF Else Statement

PHP statements are used to do different actions based on with different conditions.

PHP Statements
Whn you want to do different actions with different conditions. You can use statements to do this.

we have following four conditional statements:

if  Statement– One action with one statement

Syntex
if (condition) {
If condition is true Action to be executed;
}
Example
<?php
$var=5;

if ($var < "10") {
echo "Action Excuted!";
}
?>

if else statement – Two action using statement one is true action else false action

Syntax
if (condition) {
Action to be executed if condition is true;
} else {
Action to be executed if condition is false;
}
The example below will output “Have a good day!” if the current time is less than 20, and “Have a good night!” otherwise:

Example
<?php
$var=5;

if ($var < "10") {
echo "True Action executed!";
} else {
echo "False Action executed!";
}
?>

if elseif else statement – executes multiple action with multiple statement

Syntax
if (condition) {
Action to be executed if this condition is true;
} elseif (condition) {
Action to be executed if this condition is true;
} else {
Action to be executed if all conditions are false;
}
Example
<?php
$var=5;

if ($var < "10") {
echo "First action executed";
} elseif ($var < "15") {
echo "Second action executed!";
} else {
echo "False action executed!";
}
?>

Switch statement – execute one true action with multiple statement

Syntax
switch (n) {
case 1:
Action 1 if n=1;
break;
case 2:
Action 2 if n=2;
break;
case 3:
Action 3 if n=3;
break;

default:
Action executed if n is different from all match;
}

Example
<?php
$color = "Yellow";

switch ($color) {
case "red":
echo "Your favorite color is red!";
break;
case "yello":
echo "Your favorite color is blue!";
break;
case "green":
echo "Your favorite color is green!";
break;
default:
echo "Your favorite color is neither red, yello, nor green!";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *