Web Development /PHP Programming / Lesson
Web Development

Conditional Statements

Learn how PHP conditional statements control program flow using if, else, elseif, nested conditions, alternative syntax, switch, match, logical operators, and practical decision-making patterns.

🎯

Learning Objectives

["Explain the purpose of conditional statements in PHP.","Write basic if statements using Boolean expressions.","Use else to provide an alternative execution path.","Use elseif to evaluate multiple conditions.","Create nested conditional statements when decision logic requires multiple levels.","Combine conditions using comparison and logical operators.","Use the switch statement for multiple fixed-value choices.","Understand the modern match expression and how it differs from switch.","Use alternative PHP syntax appropriately in templates and mixed PHP\/HTML files.","Write readable, secure, and maintainable conditional logic."]

📖

Lesson Content

Introduction to Conditional Statements

Conditional statements allow a PHP program to make decisions. Instead of executing every instruction in exactly the same way, PHP can evaluate a condition and decide which block of code should run.

For example, a website may need to:

  • Display a different message depending on whether a user is logged in.
  • Allow access only when a user has the required permission.
  • Determine whether a student passed or failed.
  • Apply a discount when an order reaches a certain amount.
  • Display different content based on a selected option.

PHP provides several tools for conditional logic, including if, else, elseif, switch, and the modern match expression.


1. The if Statement

The if statement executes a block of code only when its condition evaluates to true.

Basic structure:

if (condition) {
    // Code runs when condition is true
}

Example:

$age = 20;

if ($age >= 18) {
    echo 'You are eligible.';
}

Since $age is greater than or equal to 18, PHP executes the code inside the if block.

Boolean Conditions

Conditions normally produce a Boolean result.

$is_logged_in = true;

if ($is_logged_in) {
    echo 'Welcome back!';
}

When the variable contains true, the block executes.


2. Comparison Operators in Conditions

Conditional statements frequently use comparison operators.

$score = 75;

if ($score >= 50) {
    echo 'Pass';
}

Other common comparisons include:

$age == 18;
$age === 18;
$age != 18;
$age !== 18;
$age > 18;
$age < 18;
$age >= 18;
$age <= 18;

Strict comparisons such as === are often useful when both value and type matter.


3. The else Statement

The else block runs when the if condition is false.

$age = 16;

if ($age >= 18) {
    echo 'You are an adult.';
} else {
    echo 'You are a minor.';
}

Only one of these two blocks executes.

Practical Example

$score = 42;

if ($score >= 50) {
    echo 'Congratulations! You passed.';
} else {
    echo 'You did not pass.';
}

This type of logic is useful in grading systems, validation systems, access control, and many other applications.


4. The elseif Statement

The elseif statement allows PHP to test another condition when the previous condition was false.

$score = 75;

if ($score >= 80) {
    echo 'Grade A';
} elseif ($score >= 70) {
    echo 'Grade B';
} elseif ($score >= 60) {
    echo 'Grade C';
} elseif ($score >= 50) {
    echo 'Grade D';
} else {
    echo 'Grade F';
}

PHP checks the conditions from top to bottom. Once it finds a condition that is true, its corresponding block executes and the remaining branches are skipped.


5. Multiple Conditions with Logical Operators

Conditions can be combined using logical operators.

Logical AND

$age = 25;
$has_id = true;

if ($age >= 18 && $has_id) {
    echo 'Access granted.';
}

Both conditions must be true.

Logical OR

$is_admin = false;
$is_manager = true;

if ($is_admin || $is_manager) {
    echo 'Management access granted.';
}

At least one condition must be true.

Logical NOT

$logged_in = false;

if (!$logged_in) {
    echo 'Please log in.';
}

The ! operator reverses a Boolean value.


6. Nested if Statements

A nested conditional is an if statement placed inside another conditional block.

$age = 25;
$has_account = true;

if ($age >= 18) {

    if ($has_account) {
        echo 'You may continue.';
    } else {
        echo 'Please create an account.';
    }

} else {
    echo 'You must meet the minimum age requirement.';
}

Nested conditions can be useful, but excessive nesting can make code difficult to understand. When possible, simplify complicated conditions using logical operators or well-named helper functions.


7. Combining Conditions with Parentheses

Parentheses can make complicated conditions easier to understand and can explicitly control the intended grouping.

$age = 22;
$has_ticket = true;
$is_invited = false;

if ($age >= 18 && ($has_ticket || $is_invited)) {
    echo 'Entry allowed.';
}

Here, the person must be at least 18 and must either have a ticket or be invited.

Breaking complicated conditions into named variables can sometimes improve readability:

$is_old_enough = $age >= 18;
$has_access = $has_ticket || $is_invited;

if ($is_old_enough && $has_access) {
    echo 'Entry allowed.';
}

8. Checking Multiple Values

You can use logical OR when a variable can have several acceptable values.

$role = 'editor';

if ($role === 'admin' || $role === 'editor') {
    echo 'You can manage content.';
}

For a small number of conditions this is fine. When there are many fixed choices, switch or match may provide clearer code.


9. Truthy and Falsy Values

PHP allows certain values to be evaluated as false in Boolean contexts.

Common values considered false include:

  • false
  • 0
  • 0.0
  • '' — an empty string
  • '0'
  • [] — an empty array
  • null

Example:

$name = '';

if ($name) {
    echo 'Name provided.';
} else {
    echo 'Name is empty.';
}

However, when precise validation is required, use explicit comparisons rather than relying on truthiness.

if ($name !== '') {
    echo 'Name provided.';
}

10. Conditional Statements and User Input

Conditional statements are commonly used to validate information submitted by users.

$username = $_POST['username'] ?? '';
$password = $_POST['password'] ?? '';

if ($username === '' || $password === '') {
    echo 'Both fields are required.';
} else {
    echo 'Input received.';
}

In a production application, input should be validated and processed securely. Conditional statements are only one part of a complete validation strategy.


11. The switch Statement

The switch statement is useful when one value needs to be compared against several fixed cases.

$day = 'Monday';

switch ($day) {
    case 'Monday':
        echo 'Start of the work week.';
        break;

    case 'Friday':
        echo 'End of the work week.';
        break;

    case 'Saturday':
    case 'Sunday':
        echo 'Weekend.';
        break;

    default:
        echo 'Regular weekday.';
}

The break statement prevents execution from continuing into the next case.

The default Case

The default block runs when none of the cases match.

$role = 'guest';

switch ($role) {
    case 'admin':
        echo 'Administrator';
        break;

    case 'editor':
        echo 'Editor';
        break;

    default:
        echo 'Standard user';
}

12. switch and Multiple Cases

Several cases can share the same code.

$status = 'pending';

switch ($status) {
    case 'pending':
    case 'processing':
        echo 'Your order is being processed.';
        break;

    case 'completed':
        echo 'Your order is complete.';
        break;

    case 'cancelled':
        echo 'Your order was cancelled.';
        break;

    default:
        echo 'Unknown order status.';
}

This is useful when different values should result in the same action.


13. The Modern match Expression

Modern PHP provides the match expression as a concise alternative for many fixed-value decisions.

$role = 'editor';

$message = match ($role) {
    'admin' => 'Administrator access',
    'editor' => 'Content editor access',
    'student' => 'Student access',
    default => 'Standard access',
};

echo $message;

match is an expression, so it can directly produce a value.

match Uses Strict Comparison

match compares values strictly. This is different from the traditional behavior of switch.

$value = 1;

$result = match ($value) {
    1 => 'Integer one',
    '1' => 'String one',
    default => 'Other',
};

echo $result;

The integer 1 and string '1' can therefore be handled as separate cases.

Multiple Values in One match Arm

$status = 'pending';

$message = match ($status) {
    'pending', 'processing' => 'Order is active',
    'completed' => 'Order completed',
    'cancelled' => 'Order cancelled',
    default => 'Unknown status',
};

echo $message;

14. if versus switch versus match

Each conditional structure has situations where it can make code clearer.

Use if when:

  • You are evaluating ranges or complex Boolean expressions.
  • Different conditions require different logic.
  • You need multiple logical operators.
if ($score >= 50 && $attendance >= 75) {
    echo 'Eligible';
}

Use switch when:

  • You are checking one value against several cases.
  • The application needs traditional case-based control flow.

Use match when:

  • You want to map values to results.
  • You want strict comparison.
  • You are working with modern PHP.
  • You want a concise expression that returns a value.

15. Alternative Syntax for Templates

PHP provides an alternative syntax that can make conditional logic easier to read when mixing PHP with HTML.

<?php if ($logged_in): ?>

    <p>Welcome back!</p>

<?php else: ?>

    <p>Please log in.</p>

<?php endif; ?>

This syntax is especially useful in template files.

Alternative elseif and else

<?php if ($score >= 80): ?>

    <p>Grade A</p>

<?php elseif ($score >= 70): ?>

    <p>Grade B</p>

<?php else: ?>

    <p>Needs improvement</p>

<?php endif; ?>

16. The Null Coalescing Operator in Conditions

The null coalescing operator can help safely obtain optional values before making decisions.

$role = $_GET['role'] ?? 'guest';

if ($role === 'admin') {
    echo 'Administrator area';
} else {
    echo 'Standard area';
}

This avoids directly assuming that an optional array key exists.


17. Ternary Operator as a Conditional Expression

The ternary operator can be used for short conditional choices.

$age = 20;

$message = ($age >= 18)
    ? 'Adult'
    : 'Minor';

echo $message;

It is useful when the decision is simple and both outcomes are short.

For larger blocks of logic, a normal if/else structure is usually clearer.


18. Practical Example: Student Grading System

<?php

$score = 82;

if ($score >= 80) {
    $grade = 'A';
    $remark = 'Excellent';
} elseif ($score >= 70) {
    $grade = 'B';
    $remark = 'Very Good';
} elseif ($score >= 60) {
    $grade = 'C';
    $remark = 'Good';
} elseif ($score >= 50) {
    $grade = 'D';
    $remark = 'Pass';
} else {
    $grade = 'F';
    $remark = 'Fail';
}

echo "Grade: " . $grade . "<br>";
echo "Remark: " . $remark;

This example demonstrates how conditional statements can transform a numerical score into meaningful application output.


19. Practical Example: User Access Control

<?php

$role = 'editor';
$is_logged_in = true;

if (!$is_logged_in) {
    echo 'Please log in.';
} elseif ($role === 'admin') {
    echo 'Welcome to the administrator dashboard.';
} elseif ($role === 'editor') {
    echo 'Welcome to the content dashboard.';
} else {
    echo 'Welcome to your account.';
}

This illustrates how conditions can be combined to control what different users see.

In real applications, access control should be enforced on the server side and should not rely only on hiding interface elements.


20. Practical Example: Discount System

<?php

$order_total = 75000;

if ($order_total >= 100000) {
    $discount_rate = 0.15;
} elseif ($order_total >= 50000) {
    $discount_rate = 0.10;
} elseif ($order_total >= 20000) {
    $discount_rate = 0.05;
} else {
    $discount_rate = 0;
}

$discount = $order_total * $discount_rate;
$final_total = $order_total - $discount;

echo "Discount: ₦" . $discount . "<br>";
echo "Final Total: ₦" . $final_total;

This example demonstrates conditional ranges and arithmetic operations working together.


21. Avoiding Deeply Nested Conditions

Deep nesting can make code difficult to read.

For example:

if ($user_exists) {

    if ($is_active) {

        if ($has_permission) {
            echo 'Access granted.';
        }

    }

}

In many cases, the logic can be simplified:

if ($user_exists && $is_active && $has_permission) {
    echo 'Access granted.';
}

Another useful technique is to move complicated decisions into functions. This can make the main application flow much easier to understand.


22. Guard Conditions

A guard condition checks for a situation that should stop further processing.

if (!$is_logged_in) {
    echo 'Please log in.';
    exit;
}

echo 'Protected content';

This approach can reduce unnecessary nesting and make the main path of execution easier to follow.


23. Common Conditional Statement Mistakes

Mistake 1: Using = Instead of Comparison

The assignment operator = is not the same as a comparison operator.

$age = 20;

if ($age === 20) {
    echo 'Correct comparison';
}

Mistake 2: Forgetting Braces

Although PHP allows some control structures to be written without braces, braces make code safer and easier to maintain.

if ($is_logged_in) {
    echo 'Welcome';
}

Mistake 3: Incorrect Condition Order

When using ranges, conditions should normally be ordered carefully so that a more specific condition is not prevented from being reached.

if ($score >= 80) {
    echo 'A';
} elseif ($score >= 70) {
    echo 'B';
} elseif ($score >= 50) {
    echo 'Pass';
} else {
    echo 'Fail';
}

Mistake 4: Overcomplicated Conditions

Very long conditions can be difficult to debug. Consider assigning meaningful Boolean expressions to variables or moving logic into functions.

Mistake 5: Trusting User Input

Conditional logic should never be treated as a replacement for proper security controls or input validation.


24. Practical Mini Project: Course Enrollment Check

<?php

$age = 21;
$has_completed_payment = true;
$course_available = true;

if (!$course_available) {

    echo 'This course is currently unavailable.';

} elseif (!$has_completed_payment) {

    echo 'Please complete your payment.';

} elseif ($age < 16) {

    echo 'You do not meet the minimum age requirement.';

} else {

    echo 'Enrollment successful.';

}

This example demonstrates how several conditions can be evaluated in sequence.


25. Practical Mini Project: Menu Selection with match

<?php

$menu = 'courses';

$page_title = match ($menu) {
    'home' => 'Home',
    'courses' => 'Our Courses',
    'about' => 'About Us',
    'contact' => 'Contact Us',
    default => 'Page Not Found',
};

echo $page_title;

The match expression is particularly convenient when mapping a known value to a result.


26. Best Practices for Conditional Logic

  • Use meaningful variable names in conditions.
  • Use strict comparison when appropriate.
  • Keep conditions simple and readable.
  • Use parentheses to clarify complex Boolean expressions.
  • Use braces consistently around conditional blocks.
  • Avoid unnecessary nesting.
  • Use switch or match when they make multiple fixed choices clearer.
  • Use the ternary operator only for simple expressions.
  • Validate external input before making important decisions based on it.
  • Do not rely on client-side conditions for server-side security.
  • Test both expected and unexpected values.
  • Use default branches where appropriate to handle unknown values.

27. Lesson Summary

Conditional statements are essential to PHP because they allow applications to make decisions and respond differently to different situations.

The if statement handles a basic condition. The else statement provides an alternative when the condition is false, while elseif allows multiple conditions to be tested.

The switch statement is useful for multiple fixed-value choices, while the modern match expression provides a concise, strict, value-producing alternative for many such situations.

Logical operators can combine conditions, parentheses can clarify complex expressions, and good structure can prevent deeply nested and difficult-to-maintain code.

Understanding conditional statements prepares you for more advanced PHP concepts such as loops, functions, form processing, authentication, database operations, and object-oriented programming.

💻

Code Example

<?php

$score = 82;

if ($score >= 80) {
    $grade = 'A';
    $remark = 'Excellent';
} elseif ($score >= 70) {
    $grade = 'B';
    $remark = 'Very Good';
} elseif ($score >= 60) {
    $grade = 'C';
    $remark = 'Good';
} elseif ($score >= 50) {
    $grade = 'D';
    $remark = 'Pass';
} else {
    $grade = 'F';
    $remark = 'Fail';
}

echo "Grade: " . $grade . "<br>";
echo "Remark: " . $remark;
⭐

Key Takeaways

["Conditional statements allow PHP programs to make decisions.","The if statement executes code when its condition is true.","The else statement provides an alternative when the if condition is false.","The elseif statement allows multiple conditions to be evaluated in sequence.","Logical operators can combine multiple conditions.","Nested conditions should be used carefully because excessive nesting reduces readability.","The switch statement is useful for checking one value against several fixed cases.","The modern match expression uses strict comparison and returns a value.","The ternary operator is useful for simple conditional expressions.","Clear, readable conditional logic improves maintainability, debugging, and application reliability."]

Enjoying this lesson?

Sign in to your Dwallnet Academy student account to track your learning progress and mark lessons as complete.

Sign In to Track Progress