PHP If-Else Statements

The if-else statement in PHP allows you to execute different code blocks based on conditions. This is useful when your program needs to make decisions.

🛠 Syntax of If-Else Statement

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

📝 Example 1: Basic If-Else Statement

Let’s check if a number is positive or negative.

<?php
$number = -5;
if ($number > 0) {
    echo "The number is positive.";
} else {
    echo "The number is negative.";
}
?>
    

Try It Now

📝 Example 2: If-Else with User Input

Check if a user is an adult or a minor.

<?php
$age = 20;
if ($age >= 18) {
    echo "You are an adult.";
} else {
    echo "You are a minor.";
}
?>
    

Try It Now

📝 Example 3: If-Else with Multiple Conditions (Elseif)

Use elseif to check multiple conditions.

<?php
$score = 85;
if ($score >= 90) {
    echo "Grade: A";
} elseif ($score >= 80) {
    echo "Grade: B";
} elseif ($score >= 70) {
    echo "Grade: C";
} else {
    echo "Grade: F";
}
?>
    

Try It Now

🎯 Quick Summary

  • if → Executes code if the condition is true.
  • else → Executes code if the condition is false.
  • elseif → Adds more conditions before reaching else.

📝 Practice Time!

Modify the examples above and try different conditions to see how the if-else statement works in PHP. Experiment and have fun! 🚀