Articles → PHP → Conditional Statements In PHP
Conditional Statements In PHP
Software Requirement
- XAMPP is installed on your machine
- Any text editor like Notepad
Technical Knowledge
- How PHP works?
- Basic knowledge of any programming language will help
What Are Conditional Statements?
- If there is no client call in the evening (Condition), I will go to a movie (Action)
- If you want to play games (Condition) then we will go to the gaming zone (Action) otherwise we will go home (Action if the condition is not met)
- If air tickets are cheap (Condition) then I will go by flight (Action) or if train tickets are available (Condition) then I will go by train (Action) else I will hire a cab (Action if both the Conditions are not met)
Types Of Conditional Statements In PHP
- If statement → executes some code if a certain condition is true
- If..else statement → Execute some code if the condition is true or execute some other code if the condition is false
- If..elseif..else statement → Executes some code based on which condition is true
- Switch statement → Similar to if..elseif..else statement switch statement executes some code based on which condition is true. There is a difference between if..else and switch statement which will be covered in the last section
If Statement
if (condition) {
code to be executed if condition is true;
}
<html><body>
<?php
$is_client_call = True;
if ($is_client_call == True)
{
echo "I will go for movie";
}
?></body></html>
If..Else Statement
if (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<html><body>
<?php
$wish_to_play_game = True;
if ($wish_to_play_game == True)
{
echo "Go to gaming zone";
}
else
{
echo "Go Home";
}
?></body></html>
If..Elseif..Else Statement
if (condition) {
code to be executed if condition is true;
} elseif (condition) {
code to be executed if condition is true;
} else {
code to be executed if condition is false;
}
<html><body>
<?php
$cheap_air_tickets = False;
$train_tickets_available = True;
if ($cheap_air_tickets == True)
{
echo "Go by flight";
}
elseif ($train_tickets_available == True)
{
echo "Go by train";
}
else
{
echo "Hire a cab";
}
?></body></html>
Switch Statement
switch (n) {
case label1:
code to be executed if n=label1;
break;
case label2:
code to be executed if n=label2;
break;
case label3:
code to be executed if n=label3;
break;
...
default:
code to be executed if n is different from all labels;
}
<html><body>
<?php
$mode = "TRAIN";
switch ($mode)
{
case "FLIGHT":
echo " I will go by flight";
break;
case "CAB":
echo " I will go by Cab";
break;
default:
echo " I will go by Train";
}
?></body></html>
Difference Between If..Else And Switch Statement
- In the case of the switch statement, we cannot apply logical operators like less than, greater than, etc.
- Switch statements can only contain constant values
- Switch statement is quicker in execution as compared to if..else