PHP If Else Statements – Complete Beginner Tutorial
One of the greatest strengths of PHP is its ability to make decisions. Instead of executing every line of code, PHP can evaluate conditions and choose which code should run. This process is known as conditional execution.
Decision-making is used everywhere in modern web applications. For example, checking whether a user is logged in, determining if a product is in stock, validating a form, or calculating discounts all rely on conditional statements.
What is an If Statement?
An if statement tells PHP to execute a block of code only if a specified condition evaluates to true.
Syntax:
<?php
if(condition)
{
// code to execute
}
?>
Your First If Statement
<?php
$age = 20;
if($age >= 18)
{
echo "You are an adult.";
}
?>
Output:
You are an adult.
If the condition is false, PHP simply skips the block.
Understanding Conditions
A condition is an expression that returns either true or false.
Examples:
| Condition | Result |
|---|---|
| 5 > 3 | true |
| 10 == 10 | true |
| 15 < 5 | false |
| $age >= 18 | Depends on value |
Checking User Login
A common use of an if statement is to verify whether a user has logged in.
<?php
$loggedIn = true;
if($loggedIn)
{
echo "Welcome back!";
}
?>
Using Comparison Operators
Conditions usually use comparison operators.
| Operator | Description |
|---|---|
| == | Equal to |
| === | Equal value and type |
| != | Not equal |
| > | Greater than |
| < | Less than |
| >= | Greater than or equal |
| <= | Less than or equal |
Checking a Password
<?php
$password = "secret123";
if($password == "secret123")
{
echo "Access Granted";
}
?>
The Else Statement
Sometimes you want one block of code to run when the condition is true and another when it is false. This is where the else statement is used.
Syntax:
<?php
if(condition)
{
// true
}
else
{
// false
}
?>
Example
<?php
$temperature = 15;
if($temperature >= 20)
{
echo "Warm Weather";
}
else
{
echo "Cool Weather";
}
?>
Output:
Cool Weather
Real World Example – Hotel Availability
<?php
$roomsAvailable = 5;
if($roomsAvailable > 0)
{
echo "Rooms Available";
}
else
{
echo "Fully Booked";
}
?>
Tip:
Always use clear and descriptive variable names such as $isLoggedIn, $hasPaid, or $roomsAvailable. Your code will be much easier to understand.
Using Braces
Even if an if statement contains only one line, it is considered good practice to always use curly braces.
<?php
if($score >= 50)
{
echo "Pass";
}
?>
This makes your code easier to maintain and reduces the chance of introducing errors when adding new statements later.
The Elseif Statement
Sometimes two choices are not enough. The elseif statement allows PHP to test multiple conditions until one of them is true.
Syntax:
<?php
if(condition1)
{
// code
}
elseif(condition2)
{
// code
}
else
{
// code
}
?>
Example – Student Grades
<?php
$marks = 72;
if($marks >= 80)
{
echo "Grade A";
}
elseif($marks >= 60)
{
echo "Grade B";
}
elseif($marks >= 40)
{
echo "Grade C";
}
else
{
echo "Failed";
}
?>
Output:
Grade B
Using Multiple Conditions (AND)
The && operator means both conditions must be true.
<?php
$age = 25;
$passport = true;
if($age >= 18 && $passport)
{
echo "Eligible to Travel";
}
?>
Using Multiple Conditions (OR)
The || operator means only one condition needs to be true.
<?php
$isAdmin = false;
$isManager = true;
if($isAdmin || $isManager)
{
echo "Access Allowed";
}
?>
Using the NOT Operator
The ! operator reverses a Boolean value.
<?php
$loggedIn = false;
if(!$loggedIn)
{
echo "Please log in.";
}
?>
Nested If Statements
An if statement can contain another if statement.
<?php
$loggedIn = true;
$isAdmin = true;
if($loggedIn)
{
if($isAdmin)
{
echo "Welcome Administrator";
}
}
?>
Nested statements should be used carefully because excessive nesting can make code difficult to read.
Real World Example – Tour Booking
<?php
$availableSeats = 8;
$passportValid = true;
if($availableSeats > 0 && $passportValid)
{
echo "Booking Confirmed";
}
else
{
echo "Booking Cannot Be Processed";
}
?>
Example – Discount Calculator
<?php
$total = 1200;
if($total >= 1000)
{
echo "10% Discount Applied";
}
else
{
echo "No Discount";
}
?>
Checking Form Input
Conditional statements are commonly used to validate forms.
<?php
$name = $_POST['name'] ?? "";
if($name == "")
{
echo "Please enter your name.";
}
else
{
echo "Welcome " . $name;
}
?>
Checking Multiple User Roles
<?php
$role = "editor";
if($role == "admin")
{
echo "Full Access";
}
elseif($role == "editor")
{
echo "Content Management Access";
}
elseif($role == "author")
{
echo "Article Writing Access";
}
else
{
echo "Limited Access";
}
?>
Common Beginner Mistakes
| Mistake | Correct Approach |
|---|---|
| Using = instead of == | Use == or === when comparing values. |
| Too many nested if statements | Keep conditions simple and readable. |
| Missing braces | Always use braces even for a single statement. |
| Comparing different data types unintentionally | Prefer === for strict comparisons. |
Best Practices
- Keep conditions simple.
- Use meaningful variable names.
- Prefer === over == when appropriate.
- Avoid deeply nested code.
- Validate user input before processing it.
- Add comments for complex business rules.
Practice Exercises
- Create a program that determines whether someone can vote.
- Create a grade calculator using if…elseif.
- Check whether a hotel room is available.
- Display different messages for Admin, Editor and Visitor.
- Create a simple login checker using a username and password.
- Display “Even” or “Odd” based on a number entered by the user.
Summary
The if, else, and elseif statements allow PHP programs to make intelligent decisions. Whether you’re validating forms, checking login credentials, calculating discounts, or controlling access to different parts of a website, conditional statements are one of the most frequently used features of PHP. Mastering them is an essential step toward becoming a confident PHP developer.
Frequently Asked Questions
What is the purpose of an if statement?
An if statement executes code only when a specified condition is true.
When should I use elseif?
Use elseif when you need to test more than two possible conditions.
What is the difference between if and switch?
An if statement is more flexible and can evaluate complex conditions, while a switch statement is ideal for comparing one value against multiple fixed options.
Can I combine multiple conditions?
Yes. Use logical operators such as && (AND) and || (OR).
Should I always use braces?
Yes. Even when only one line of code is executed, braces improve readability and help prevent future bugs.
Mini Project
Create a travel booking eligibility checker.
Your program should:
- Ask for the traveller’s age.
- Check whether a passport is valid.
- Verify whether seats are available.
- Display “Booking Confirmed” or an appropriate error message based on the conditions.
Interview Questions
- What is the difference between if and elseif?
- What does the && operator do?
- When would you use the || operator?
- Why is === preferred over ==?
- What are nested if statements?
Next Tutorial
Now that you know how to make decisions, the next step is learning the PHP Switch Statement, which provides a cleaner way to handle multiple fixed conditions.
Next: PHP Switch Statement