Back to Blog
Lesson 5 of the PHP: Modern PHP from the Ground Up course
PHPJuly 16, 20264 min read

Mastering Conditional Logic with If-Else in PHP

Learn to control program flow with PHP if-else statements. Master boolean logic and decision-making to build dynamic, responsive backend applications.

PHPbackendprogrammingconditionalscontrol structures
Close-up of PHP code on a monitor, highlighting development and programming concepts.

Previously in this course, we explored variables and data types and how to manage them using strong typing and scalar type hints. Now that you can store data, you need a way to make your code "think"—executing different blocks of logic depending on the state of that data.

In software development, we call these control structures. They are the steering wheel of your application, allowing your server-side scripts to react to user input, database results, or system states.

Understanding Boolean Logic

At the heart of every decision in PHP lies boolean logic. A boolean expression always evaluates to either true or false. When you use an if statement, PHP checks the truthiness of the expression provided inside the parentheses.

Common comparison operators include:

  • == (equal to)
  • != (not equal to)
  • > (greater than)
  • < (less than)
  • >= (greater than or equal to)
  • <= (less than or equal to)

Writing If-Else Statements

Close-up of a statement of intent document on a marbled surface with bright pink reflections.

An if statement executes a block of code only if the condition evaluates to true. An else block provides a fallback path if the condition is false.

Here is a concrete example of checking a user's access level in our running project:

PHP
<?php
declare(strict_types=1);

$userRole = 'admin';

if ($userRole === 'admin') {
    echo "Welcome to the dashboard, administrator.";
} else {
    echo "Access denied. You do not have permission to view this page.";
}
?>

In this snippet, we use the identity operator ===, which checks both value and type, ensuring our string matches exactly. If $userRole were anything other than 'admin', the script would immediately jump to the else block.

Handling Multiple Branches with Elseif

What if you have more than two outcomes? You can chain conditions using elseif. PHP evaluates these top-to-bottom and stops at the first condition that returns true.

PHP
<?php
$userAge = 18;

if ($userAge < 13) {
    echo "Content restricted for children.";
} elseif ($userAge >= 13 && $userAge < 18) {
    echo "Teen content enabled.";
} else {
    echo "Full adult content access granted.";
}
?>

Hands-on Exercise

In your local development environment (set up in our first lesson), create a file named logic.php.

Define a variable $score with a value between 0 and 100. Write a script that outputs:

  1. "Excellent" if the score is 90 or higher.
  2. "Good" if the score is between 70 and 89.
  3. "Needs Improvement" if the score is below 70.

Common Pitfalls

  • Assignment vs. Comparison: A common beginner mistake is using a single equals sign = (assignment) instead of == or === (comparison) inside an if statement. if ($x = 5) will assign 5 to $x and evaluate to true, which is rarely what you intended.
  • Loose Typing: Using == can lead to unexpected results due to type juggling (e.g., 0 == 'apple' evaluates to true in some contexts). Always prefer === to ensure your types match.
  • Missing Braces: While PHP allows omitting curly braces {} for single-line statements, it is considered poor practice and a common source of bugs. Always use braces to define your code blocks clearly.

FAQ

Q: Can I nest if statements inside other if statements? A: Yes, this is called "nested logic." While useful, try to keep nesting shallow to maintain readability. If you find yourself nesting more than three levels deep, it's usually time to refactor.

Q: What is the difference between && and ||? A: && is the logical AND (both must be true). || is the logical OR (at least one must be true).

Q: Does it matter if I use else if or elseif? A: In PHP, they are functionally identical. elseif is the standard, cleaner syntax.

Recap

We've covered the basics of controlling program flow using if, elseif, and else. By evaluating boolean expressions, your PHP scripts can now handle different scenarios dynamically. This decision-making capability is the foundation for almost every feature you will build, from authentication to data validation.

Up next: Advanced Control Structures, where we'll look at switch statements and the ternary operator to make your logic even more concise.

Similar Posts