Conditional Statements in PHP
Conditional statements in PHP are used to execute different blocks of code based on specific conditions. These statements help make decisions within a program.
PHP supports the following conditional statements:
- if Statement – Executes code if a condition is true.
- if-else Statement – Executes one block if the condition is true, otherwise another block.
- if-elseif-else Statement – Allows multiple conditions to be checked sequentially.
- switch Statement – Selects one block of code to execute from multiple options.
1. if Statement
Definition:
The if statement checks a condition and executes a block of code only if the condition evaluates to true.
Syntax:
if (condition)
{
// Code to execute if condition is true
}
Example:
<?php
$age = 20;
if ($age >= 18)
{
echo "You are eligible to vote.";
}
?>
2. if-else Statement
Definition:
The if-else statement executes one block of code if the condition is true and another block if it is false.
Syntax:
if (condition)
{
// Code if condition is true
}
else
{
// Code if condition is false
}
Example:
<?php
$marks = 45;
if ($marks >= 50)
{
echo "You passed.";
}
else
{
echo "You failed.";
}
?>
3. if-elseif-else Statement
Definition:
The if-elseif-else statement allows multiple conditions to be checked in sequence. The first true condition's block is executed, and the remaining conditions are skipped.
Syntax:
if (condition1)
{
// Code if condition1 is true
} elseif (condition2)
{
// Code if condition2 is true
}
else
{
// Code if none of the conditions are true
}
Example:
<?php
$score = 85;
if ($score >= 90) {
echo "Grade: A";
} elseif ($score >= 75) {
echo "Grade: B";
} elseif ($score >= 60) {
echo "Grade: C";
} else {
echo "Grade: D";
}
?>
4. switch Statement
Definition:
The switch statement is used when multiple conditions need to be checked against the same variable. It provides a cleaner alternative to multiple if-elseif statements.
Syntax:
switch (variable)
{
case value1:
// Code for value1
break;
case value2:
// Code for value2
break;
default:
// Code if no case matches
}
Example:
<?php
$day = "Monday";
switch ($day)
{
case "Monday":
echo "Start of the workweek.";
break;
case "Friday":
echo "Weekend is near!";
break;
case "Sunday":
echo "It's a holiday!";
break;
default:
echo "Just another day.";
}
?>