Skip to main content
PHP for Beginners
CHAPTER 07 Beginner

PHP Conditional Statements

Updated: May 12, 2026
20 min read

# Chapter 7: PHP Conditional Statements

1. Introduction

Welcome to Chapter 7! So far, our PHP scripts have executed every single line of code from top to bottom. But real applications need to make decisions. If a user enters the correct password, log them in; otherwise, show an error. If a student's score is above 50, they pass; otherwise, they fail. Conditional statements give your code a "brain," allowing it to execute different blocks of code based on different conditions.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Use if statements to execute code when a condition is true.
  • Use else to provide a fallback when the condition is false.
  • Chain multiple conditions together using elseif.
  • Use the switch statement for evaluating a single variable against many possible values.
  • Apply conditional logic to real-world scenarios.

3. The if Statement

The if statement is the most basic conditional. It evaluates a condition (inside parentheses), and if that condition evaluates to true, it executes the code block (inside curly braces).
php
12345678
<?php
$score = 85;

if ($score >= 50) {
    echo "Congratulations! You passed the exam.";
}
// If the score was 40, nothing would happen.
?>

4. The else Statement

What if we want something to happen when the condition is false? We attach an else block to the end of our if statement.
php
123456789
<?php
$is_logged_in = false;

if ($is_logged_in) {
    echo "Welcome to your dashboard!";
} else {
    echo "Please log in to continue.";
}
?>

5. The elseif Statement

When you have more than two possibilities, you can use elseif (or else if) to check multiple conditions in sequence.
php
1234567891011
<?php
$time = 14; // 14:00 or 2 PM

if ($time < 12) {
    echo "Good morning!";
} elseif ($time < 18) {
    echo "Good afternoon!";
} else {
    echo "Good evening!";
}
?>

6. The switch Statement

If you find yourself writing a massive chain of elseif statements checking the exact same variable against different values, a switch statement is cleaner and faster.
php
1234567891011121314151617
<?php
$role = "editor";

switch ($role) {
    case "admin":
        echo "You have full access.";
        break;
    case "editor":
        echo "You can edit and publish posts.";
        break;
    case "subscriber":
        echo "You can only read posts.";
        break;
    default:
        echo "Role not recognized.";
}
?>

*Note: The break keyword stops the switch block from continuing to run the code in the cases below it. default acts like the final else fallback.*

7. Real-World Examples

Imagine an e-commerce checkout system checking shipping costs based on the country.
php
1234567891011121314
<?php
$country = "Canada";
$shipping_cost = 0;

if ($country == "USA") {
    $shipping_cost = 5.00;
} elseif ($country == "Canada" || $country == "Mexico") {
    $shipping_cost = 15.00;
} else {
    $shipping_cost = 30.00; // Rest of the world
}

echo "Your shipping cost is: $" . $shipping_cost;
?>

8. Output Explanations

In the shipping example, PHP checks the first condition ($country == "USA"). Since it is false, it moves to the elseif. It checks if the country is Canada OR Mexico. Since $country is "Canada", this condition is true. It executes the block, setting $shipping_cost to 15.00, skips the else block entirely, and proceeds to echo the final cost.

9. Common Mistakes

  • Using assignment = instead of comparison ==: Writing if ($x = 10) will actually *assign* 10 to $x, and the condition will evaluate to true regardless of what $x originally was! Always use == or ===.
  • Forgetting curly braces: While PHP allows omitting curly braces for single-line if statements, it is highly prone to bugs. Always use { }.
  • Forgetting break in a switch: If you forget break, PHP will execute the matched case AND every single case below it (known as fall-through).

10. Best Practices

  • Early Return/Bail Early: If testing for errors, put them at the top of your script. If there is an error, stop the script, reducing the need for massively nested if statements.
  • Strict Comparison: Use === instead of == to prevent unexpected type juggling bugs.

11. Exercises

  1. 1. Write an if/else statement that checks if a $temperature variable is above 30. Output "It's hot" if true, "It's cold" if false.
  1. 2. Write a switch statement that takes a variable $day = "Monday" and echoes whether it is a weekday or weekend.

12. Mini Project: Grade Checker

Task: Build a script that takes a numerical student score and assigns a letter grade based on specific ranges.
php
123456789101112131415161718192021222324252627282930313233343536373839
<?php
// Inputs
$student_name = "Sarah";
$score = 82;
$grade = "";

// Logic
if ($score >= 90) {
    $grade = "A";
} elseif ($score >= 80) {
    $grade = "B";
} elseif ($score >= 70) {
    $grade = "C";
} elseif ($score >= 60) {
    $grade = "D";
} else {
    $grade = "F";
}
?>

<!DOCTYPE html>
<html>
<head><title>Grade Report</title></head>
<body>
    <h2>Student Grade Report</h2>
    <p>Student: <strong><?php echo $student_name; ?></strong></p>
    <p>Score: <?php echo $score; ?>%</p>
    <p>Final Grade: <strong style="color: blue;"><?php echo $grade; ?></strong></p>
    
    <?php
    // We can use another if statement for a special message
    if ($grade == "A" || $grade == "B") {
        echo "<p style=&#039;color: green;'>Excellent work!</p>";
    } elseif ($grade == "F") {
        echo "<p style=&#039;color: red;'>You must retake the class.</p>";
    }
    ?>
</body>
</html>

13. Coding Challenges

Challenge 1: Create an access control script. Variables: $age and $has_id. An if statement should check: If age is 18 or older AND they have an ID (true), echo "Access Granted". Otherwise, echo "Access Denied".
php
1234567891011
<?php
// Solution
$age = 19;
$has_id = true;

if ($age >= 18 && $has_id === true) {
    echo "Access Granted";
} else {
    echo "Access Denied";
}
?>

14. MCQs with Answers

1. What happens if an if condition is false and there is no else block? A) PHP throws a fatal error. B) PHP skips the if block and continues executing the rest of the script. C) PHP crashes the server. D) The script stops executing immediately. *Answer: B*

2. Which keyword stops a switch block from evaluating the remaining cases? A) stop B) end C) exit D) break *Answer: D*

3. Why is if ($x = 5) dangerous? A) It causes a syntax error. B) It assigns 5 to $x instead of comparing it, always resulting in true. C) It deletes the variable $x. D) It only works with strings. *Answer: B*

15. Interview Questions

Q: When should you use a switch statement instead of if/elseif/else? *A:* You should use a switch statement when you are comparing a single variable against many different literal values (like checking a specific user role, a status code, or days of the week). It makes the code much cleaner and easier to read than a massive chain of elseifs.

Q: What is the Ternary Operator in PHP? *A:* It is a shorthand way of writing a simple if/else statement on a single line. The syntax is condition ? true_value : false_value. Example: $status = ($age >= 18) ? "Adult" : "Minor";

16. FAQs

Q: Can I nest an if statement inside another if statement? *A:* Yes, absolutely! This is called "nesting." However, try to avoid nesting too deep (more than 2 or 3 levels), as it makes your code very difficult to read.

17. Summary

You've given your code a brain! You learned how to use if, else, and elseif to make complex logical decisions based on changing conditions. You also learned how to use the switch statement to efficiently route logic when checking a single variable against many possibilities.

18. Next Chapter Recommendation

Now that our code can make decisions, it's time to make it do heavy lifting. What if you need to echo something 1,000 times? In Chapter 8: PHP Loops, we will learn how to automate repetitive tasks!

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·