Spex3
    

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
}


✅ Example:


<?php
$age = 18;

if ($age >= 18) {
echo "You are eligible to vote.";
}
?>


📌 If $age is 18 or more, the message will be displayed.

2. if...else Statement
Executes one block of code if the condition is true and another block if the condition is false.

✅ Syntax:


if (condition) {
// Code if condition is true
} else {
// Code if condition is false
}


✅ Example:


<?php
$temperature = 25;

if ($temperature > 30) {
echo "It's a hot day.";
} else {
echo "The weather is pleasant.";
}
?>


📌 If $temperature is more than 30, "It's a hot day" will be displayed; otherwise, "The weather is pleasant" will be displayed.

3. if...elseif...else Statement
Checks multiple conditions and executes different blocks of code accordingly.

✅ 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
$marks = 85;

if ($marks >= 90) {
echo "Grade: A+";
} elseif ($marks >= 80) {
echo "Grade: A";
} elseif ($marks >= 70) {
echo "Grade: B";
} else {
echo "Grade: C";
}
?>


📌 This program assigns grades based on marks.

4. switch Statement
The switch statement is an alternative to multiple if...elseif conditions. It checks a variable against multiple values and executes the matching case.

✅ Syntax:


switch (expression) {
case value1:
// Code if expression == value1
break;
case value2:
// Code if expression == 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 rest day!";
break;
default:
echo "It's a regular day.";
}
?>


📌 The message will depend on the value of $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


Conclusion
Use if-else for complex conditions.

Use switch when comparing a single variable with multiple fixed values.


    Date: 2025-03-28 00:00:00.000000