Skip to main content

Course Progress

Loading...

Understanding PHP Conditionals: If-Else Statements

Duration: 30 minutes
Module 2: Control Structures

Learning Objectives

  • Master PHP programming concepts
  • Write clean, maintainable code
  • Apply best practices
  • Build dynamic applications

Introduction to If-Else Statements

Welcome to our continuing exploration of PHP conditional statements! In our previous session, we learned about basic if statements that execute code when a condition is true. Today, we're expanding our toolkit with if-else statements, which allow us to execute different code blocks based on whether a condition is true or false.

The Fork in the Road Analogy

Think of an if-else statement as a fork in the road. When your program reaches this fork, it evaluates a condition to decide which path to take. If the condition is true, it takes one path (the "if" path); if the condition is false, it takes the alternative path (the "else" path). Unlike a simple if statement, which may or may not execute code, an if-else statement always executes exactly one of its two code blocks.

Diagram
False >|False| C[Else Block Executes] B Condition Check If Block Executes Else Block Executes Continue Program

Basic If-Else Syntax

The if-else statement expands on the basic if statement by adding a secondary code block that executes when the condition is false.

Basic Syntax


if (condition) {
    // Code to execute if condition is true
} else {
    // Code to execute if condition is false
}
                

Let's break down the components:

  • if: The keyword that starts the conditional statement
  • condition: An expression that evaluates to either true or false
  • { }: First set of curly braces enclosing the code block to execute if the condition is true
  • else: The keyword that introduces the alternative code block
  • { }: Second set of curly braces enclosing the code block to execute if the condition is false

Real-World Example: User Authentication

Building on our previous example, let's enhance our user authentication to provide feedback when login fails:


$username = "user_input";
$password = "user_password";

// Check if the entered credentials are correct
if ($username === "admin" && $password === "secure_password") {
    echo "Login successful! Welcome to the dashboard.";
} else {
    echo "Login failed. Please check your username and password.";
}
                

Now the user gets feedback whether their login attempt is successful or not.

When to Use If-Else Statements

If-else statements are perfect for binary situations where exactly one of two possible actions should be taken based on a condition.

Binary Decision Making

Condition? False True If Block Else Block

Common Use Cases

  • Form Validation: Showing success messages or error feedback
  • Authentication: Allowing or denying access
  • User Interface: Showing different UI elements based on user state
  • Data Processing: Handling expected vs. unexpected data formats
  • Toggling Features: Enabling or disabling functionality

Practical Examples of If-Else Statements

Age Verification with Feedback

Let's enhance our age verification example to provide feedback in both cases:


$userAge = 16;
$minimumAge = 18;

if ($userAge >= $minimumAge) {
    echo "Welcome! You have access to all content.";
} else {
    echo "Sorry, you must be at least {$minimumAge} years old to access this content.";
}
                

Form Validation with Specific Feedback

Providing specific feedback for a required field:


$email = $_POST['email'] ?? '';

if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Email validation passed!";
} else {
    echo "Please enter a valid email address.";
}
                

Stock Availability Check

Checking if a product is in stock and displaying appropriate messages:


$stockQuantity = 0;

if ($stockQuantity > 0) {
    echo "Item is in stock. You can add it to your cart.";
} else {
    echo "Sorry, this item is currently out of stock. You can sign up for notifications.";
}
                

WordPress-Specific Example: Checking for Featured Images

In WordPress theme development, a common task is checking for featured images:


// WordPress function to check if post has a featured image
if (has_post_thumbnail()) {
    // Display the featured image
    the_post_thumbnail('large');
} else {
    // Display a default image
    echo '<img src="default-image.jpg" alt="Default featured image">';
}
                

Single-Line If-Else Statements

For simple if-else statements, PHP allows you to omit the curly braces if you only have one statement to execute in each block:


// Standard form
if ($isLoggedIn) {
    echo "Welcome back!";
} else {
    echo "Please log in.";
}

// Single-line form
if ($isLoggedIn) echo "Welcome back!"; else echo "Please log in.";
                

Best Practice: Use Braces

As with single-line if statements, it's generally recommended to always use curly braces even for simple if-else statements. This promotes consistency and prevents potential bugs when code is modified later.

Alternative Syntax for Templates

Just like with if statements, PHP offers an alternative syntax for if-else statements that's particularly useful in template files:


<!-- Standard syntax -->
<?php
if ($isLoggedIn) {
    echo "<h1>Welcome back, {$username}!</h1>";
} else {
    echo "<h1>Welcome, guest!</h1>";
}
?>

<!-- Alternative syntax -->
<?php if ($isLoggedIn): ?>
    <h1>Welcome back, <?php echo $username; ?>!</h1>
<?php else: ?>
    <h1>Welcome, guest!</h1>
<?php endif; ?>
                

WordPress Theme Example: Primary/Secondary Content

This is commonly used in WordPress themes to show primary content when available or fallback content when it's not:


<?php if (have_posts()): ?>
    <!-- Display posts loop -->
    <?php while (have_posts()): the_post(); ?>
        <article>
            <h2><?php the_title(); ?></h2>
            <?php the_content(); ?>
        </article>
    <?php endwhile; ?>
<?php else: ?>
    <!-- No posts found -->
    <div class="no-results">
        <h2>No posts found</h2>
        <p>Sorry, no posts matched your criteria.</p>
    </div>
<?php endif; ?>
                

Using If-Else for Conditional Assignment

One common use of if-else statements is to assign different values to a variable based on a condition:

Basic Conditional Assignment


// Determine discount percentage based on order amount
$orderTotal = 120;
$discountPercentage;

if ($orderTotal >= 100) {
    $discountPercentage = 10; // 10% discount
} else {
    $discountPercentage = 5; // 5% discount
}

echo "Your discount is {$discountPercentage}%";
                

Preview: The Ternary Operator

In our upcoming session on the ternary operator, we'll learn a more concise way to write conditional assignments:


// Same logic as above, but using the ternary operator
$orderTotal = 120;
$discountPercentage = ($orderTotal >= 100) ? 10 : 5;

echo "Your discount is {$discountPercentage}%";
                

This performs the same function as the if-else statement but in a more compact form. We'll explore this in more detail in a future session.

Nested If-Else Statements

Sometimes you'll need to check multiple conditions in sequence. This can be done by nesting if-else statements inside one another:

Basic Nested If-Else


$userAge = 25;
$hasSubscription = true;

if ($userAge >= 18) {
    if ($hasSubscription) {
        echo "Access granted to premium content.";
    } else {
        echo "Please subscribe to access premium content.";
    }
} else {
    echo "Age restriction: You must be 18 or older.";
}
                
Diagram
No Yes No >|No| E[Subscription Required Message] C > F E Age Restriction Message Grant Premium Access Subscription Required Message Continue Program Age >= 18? Has Subscription?

Best Practice: Avoid Deep Nesting

While nesting if-else statements is sometimes necessary, deep nesting (more than 2-3 levels) can make your code difficult to read and maintain. In our upcoming session on if-elseif-else statements, we'll learn a more readable alternative for checking multiple conditions.

Combining Conditions to Simplify Logic

Sometimes you can simplify nested if-else statements by using logical operators to combine conditions:

Before: Nested If-Else


if ($userAge >= 18) {
    if ($hasSubscription) {
        echo "Access granted to premium content.";
    } else {
        echo "Please subscribe to access premium content.";
    }
} else {
    echo "Age restriction: You must be 18 or older.";
}
                

After: Using Logical AND


if ($userAge >= 18 && $hasSubscription) {
    echo "Access granted to premium content.";
} else if ($userAge >= 18) {
    echo "Please subscribe to access premium content.";
} else {
    echo "Age restriction: You must be 18 or older.";
}
                

The second version achieves the same result but with a clearer structure. We'll explore this more in our next session on if-elseif-else statements.

Best Practices for If-Else Statements

Keep Conditions Simple

Complex conditions can be difficult to understand and debug. If your condition is getting too complex, consider breaking it down or storing intermediary results in variables with descriptive names:


// Hard to read
if (($age >= 18 && $hasParentalConsent) || ($age >= 21 && $hasValidID) || $isAdministrator) {
    // Code...
}

// Better approach
$isMinorWithConsent = $age >= 18 && $hasParentalConsent;
$isAdult = $age >= 21 && $hasValidID;
$hasAccess = $isMinorWithConsent || $isAdult || $isAdministrator;

if ($hasAccess) {
    // Code...
}
                

Be Consistent with Brace Style

PHP allows several styles for placing braces. Pick one and use it consistently throughout your codebase:


// Style 1: Opening brace on the same line
if ($condition) {
    // Code...
} else {
    // Code...
}

// Style 2: Opening brace on the next line
if ($condition)
{
    // Code...
}
else
{
    // Code...
}
                

Most PHP coding standards (including PSR-12) recommend Style 1, but consistency is the most important factor.

Pay Attention to Indentation

Proper indentation makes your code much more readable:


// Poor indentation
if ($condition) {
echo "This code is hard to read";
} else {
echo "Because the indentation is inconsistent";
echo "Or missing entirely";
}

// Good indentation
if ($condition) {
    echo "This code is easy to read";
} else {
    echo "Because the indentation is consistent";
    echo "And clearly shows the code structure";
}
                

Consider the Default Case

When using if-else, think carefully about which case should be the "else" (default) case. Generally, the most common or expected scenario should be in the "if" block, and the exceptional case in the "else" block:


// Less optimal
if ($error) {
    displayErrorMessage();
} else {
    proceedNormally();
}

// More optimal (assuming errors are rare)
if (!$error) {
    proceedNormally();
} else {
    displayErrorMessage();
}
                

Common Pitfalls and How to Avoid Them

Assignment vs. Comparison

One of the most common errors in PHP is using the assignment operator (=) instead of the comparison operator (== or ===) in conditions:


// WRONG: This always evaluates to true (unless $value is falsy)
if ($value = 10) {
    echo "This will execute!";
}

// CORRECT: This evaluates to true only if $value equals 10
if ($value == 10) {
    echo "This will execute only if $value is 10.";
}
                

The first example assigns 10 to $value and then checks if that result is truthy (which it is), rather than comparing $value to 10.

Missing Braces for Multi-line Blocks

If you omit braces, only the first statement is controlled by the if or else:


// WRONG: Only the first echo is part of the if branch
if ($isLoggedIn)
    echo "Welcome back!";
    echo "You have new messages."; // This always executes!

// CORRECT: Both echoes are part of the if branch
if ($isLoggedIn) {
    echo "Welcome back!";
    echo "You have new messages.";
}
                

Forgetting that 0 and Empty Strings are Falsy

Be careful when checking numeric or string variables that might legitimately be 0 or empty:


$count = 0;

// WRONG: This condition fails even though $count is set
if ($count) {
    echo "Items found: $count";
} else {
    echo "No items found."; // This will execute!
}

// CORRECT: Explicitly check for null or use the !== operator
if ($count !== null) {
    echo "Items found: $count"; // This will execute with 0
} else {
    echo "No items found.";
}
                

Not Using Strict Comparison When Needed

Remember the difference between loose (==) and strict (===) comparison:


$userInput = "42";

// WRONG: This will evaluate to true due to type juggling
if ($userInput == 42) {
    echo "Equal!"; // This will execute!
}

// CORRECT: This will evaluate to false because types differ
if ($userInput === 42) {
    echo "Equal!"; // This won't execute
} else {
    echo "Not equal! String vs Integer"; // This will execute
}
                

Debugging If-Else Statements

Echo Intermediate Values

When debugging conditional logic, it can be helpful to output the actual values being compared:


// Debugging approach
echo "Debug - userRole: " . $userRole . "<br>";
echo "Debug - isActive: " . ($isActive ? 'true' : 'false') . "<br>";

if ($userRole === 'editor' && $isActive) {
    echo "Access granted";
} else {
    echo "Access denied";
}
                

Use var_dump() for Complex Conditions

For more complex conditions, var_dump() shows both the value and type of variables:


$a = "5";
$b = 5;

echo "Debugging complex condition:<br>";
var_dump($a);
var_dump($b);
var_dump($a == $b);  // true (loose comparison)
var_dump($a === $b); // false (strict comparison)

if ($a === $b) {
    echo "Identical!";
} else {
    echo "Not identical!";
}
                

Isolate Conditions

For complex conditions with multiple parts, test each part separately:


$age = 25;
$hasSubscription = false;
$isSpecialPromotion = true;

// Testing each condition separately
echo "Age check: " . ($age >= 18 ? 'Pass' : 'Fail') . "<br>";
echo "Subscription check: " . ($hasSubscription ? 'Yes' : 'No') . "<br>";
echo "Special promotion: " . ($isSpecialPromotion ? 'Yes' : 'No') . "<br>";

// Combined condition
$hasAccess = ($age >= 18 && $hasSubscription) || $isSpecialPromotion;
echo "Final access decision: " . ($hasAccess ? 'Granted' : 'Denied');
                

Looking Ahead: Beyond Simple If-Else

Now that we've mastered if-else statements, our next topics will further expand our conditional toolkit:

  • If-Elseif-Else Statements: Handling multiple conditions in sequence
  • Switch Statements: An alternative when comparing a single variable against multiple values
  • Ternary Operator: A compact way to write simple if-else expressions
  • Null Coalescing Operator: A shorthand for providing default values
Diagram
If If-Else If-Elseif-Else Switch Ternary Null Coalescing

Practice Exercises

Exercise 1: Basic If-Else

Write a PHP script that checks if a variable $temperature is greater than 30°C. If it is, display "It's a hot day!", otherwise display "The temperature is pleasant."

Reveal Solution

$temperature = 32;

if ($temperature > 30) {
    echo "It's a hot day!";
} else {
    echo "The temperature is pleasant.";
}
                    

Exercise 2: Conditional Display for E-commerce

Write a PHP snippet for an e-commerce site that displays different shipping information based on order total. If the order total is $50 or more, display "Free Shipping!", otherwise display "Shipping Cost: $5.99".

Reveal Solution

$orderTotal = 45.75;
$freeShippingThreshold = 50;

if ($orderTotal >= $freeShippingThreshold) {
    echo "Free Shipping!";
} else {
    echo "Shipping Cost: $5.99";
    // You could also calculate how much more they need to spend
    $amountNeeded = $freeShippingThreshold - $orderTotal;
    echo "<br>Add $" . number_format($amountNeeded, 2) . " more to qualify for free shipping!";
}
                    

Exercise 3: WordPress Content Visibility

Write a PHP snippet for a WordPress theme that checks if a post is password protected. If it is, display a password form, otherwise display the post content.

Reveal Solution

<?php
// WordPress function to check if post is password protected
if (post_password_required()) {
    // Display the password form
    echo '<div class="password-form">';
    echo 'This content is password protected. Please enter the password to view it.';
    echo get_the_password_form();
    echo '</div>';
} else {
    // Display the post content
    echo '<div class="post-content">';
    the_content();
    echo '</div>';
}
?>
                    

Exercise 4: User Permission Levels

Create a PHP script that determines what message to show a user based on their role. If the user is an "admin", show "Welcome, Administrator. You have full access.". Otherwise, show "Welcome, User. You have limited access."

Reveal Solution

$userRole = "editor"; // Could be "admin", "editor", "subscriber", etc.

if ($userRole === "admin") {
    echo "Welcome, Administrator. You have full access.";
} else {
    echo "Welcome, User. You have limited access.";
    
    // For better user experience, you could be more specific:
    if ($userRole === "editor") {
        echo " You can create and edit content.";
    } else if ($userRole === "subscriber") {
        echo " You can read premium content.";
    }
}
                    

Additional Resources

Homework Assignment

Building on our previous homework, enhance your PHP grading system with the following requirements:

  1. Create variables for $studentName and $score (between 0 and 100)
  2. Using if-else statements, determine the letter grade based on the score:
    • 90-100: A
    • 80-89: B
    • 70-79: C
    • 60-69: D
    • Below 60: F
  3. Add a check to determine if the student passed (score >= 60) or failed
  4. Display a personalized message for the student that includes:
    • Their name
    • Their score
    • Their letter grade
    • Whether they passed or failed
    • A motivational message (different for passing and failing students)
  5. Bonus: Add checks for invalid scores and display appropriate error messages

Submit your code and a brief explanation of your solution.