PHP Control Structures: Conditional Statements

PHP Control Structures: Conditional Statements
Conditional statements allow the execution of different code blocks based on conditions. PHP provides the following conditional structures:
if statement
if...else statement
if...elseif...else statement
switch statement
1. if Statement
Executes a block of code only if the condition is true.
✅ Syntax:
if (condition) {
// Code to execute if condition is true
}
<?php
$age = 18;
if ($age >= 18) {
echo "You are eligible to vote.";
}
?>
if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}
<?php
$temperature = 25;
if ($temperature > 30) {
echo "It's a hot day.";
} else {
echo "The weather is pleasant.";
}
?>
if (condition1) {
// Code if condition1 is true
} elseif (condition2) {
// Code if condition2 is true
} else {
// Code if none of the conditions are true
}
<?php
$marks = 85;
if ($marks >= 90) {
echo "Grade: A+";
} elseif ($marks >= 80) {
echo "Grade: A";
} elseif ($marks >= 70) {
echo "Grade: B";
} else {
echo "Grade: C";
}
?>
switch (expression) {
case value1:
// Code if expression == value1
break;
case value2:
// Code if expression == value2
break;
default:
// Code if no case matches
}
<?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 rest day!";
break;
default:
echo "It's a regular day.";
}
?>
Key Differences: if-else vs switch
Feature if-else switch
Used for Complex conditions Checking one variable against multiple values
Comparison Works with logical, relational, and equality conditions Works only with equality (==)
Performance Slightly slower if many conditions Faster with many conditions
Date: 2025-03-28 00:00:00.000000