How to Use If Else in PHP: Simple Guide with Examples
In PHP, you use
if to run code when a condition is true, and else to run code when it is false. The syntax is if (condition) { ... } else { ... }. This lets your program choose between two paths based on conditions.Syntax
The if else statement in PHP lets you run different code blocks based on a condition. The if part checks if a condition is true. If it is, the code inside its block runs. If not, the else block runs instead.
Here is the basic structure:
php
<?php if (condition) { // code runs if condition is true } else { // code runs if condition is false } ?>
Example
This example checks if a number is positive or not. It prints a message based on the check.
php
<?php $number = 5; if ($number > 0) { echo "The number is positive."; } else { echo "The number is zero or negative."; } ?>
Output
The number is positive.
Common Pitfalls
Common mistakes include missing parentheses around the condition, forgetting curly braces, or using = instead of == for comparison.
Always use == or === to compare values, not = which assigns values.
php
<?php // Wrong: assignment instead of comparison $age = 20; if ($age == 18) { echo "You are 18."; } else { echo "You are not 18."; } // Right: comparison if ($age === 18) { echo "You are 18."; } else { echo "You are not 18."; } ?>
Output
You are not 18.
Quick Reference
| Part | Description |
|---|---|
| if (condition) | Checks if the condition is true |
| { ... } | Code block that runs if condition is true |
| else | Runs if the condition is false |
| { ... } | Code block that runs if condition is false |
Key Takeaways
Use if else to run code based on true or false conditions.
Always put conditions inside parentheses and code inside curly braces.
Use == or === for comparisons, not = which assigns values.
The else block runs only if the if condition is false.
Missing braces or parentheses cause syntax errors.