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."; } ?>
📝 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."; } ?>
📝 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"; } ?>
🎯 Quick Summary
if
→ Executes code if the condition istrue
.else
→ Executes code if the condition isfalse
.elseif
→ Adds more conditions before reachingelse
.
📝 Practice Time!
Modify the examples above and try different conditions to see how the if-else
statement works in PHP. Experiment and have fun! 🚀