Skip to Content
Course content

7: Control Flow Statements

Click on the "Edit" button in the top corner of the screen to edit your slide content.

I'm seeing if, switch, and this newer match expression. Which one should I actually be using?

This is a classic point of confusion because PHP has evolved quite a bit. Here is how I decide which one to reach for. Use if/elseif/else when you're dealing with complex logic, ranges (like $age > 18 && $age < 65), or conditions that aren't based on a single value.

Now, if you're just checking one variable against a list of specific values, switch used to be the go-to. But in modern PHP (8.0+), you should almost always use match instead. Why? Because match is an expression—it actually returns a value—and it uses strict comparison (===), which saves you from some really annoying bugs where the string "0" might accidentally match an integer 0.

// The old way (switch)
switch ($userRole) {
    case 'admin':
        $access = 'full';
        break;
    case 'editor':
        $access = 'limited';
        break;
    default:
        $access = 'none';
}

// The modern way (match)
$access = match ($userRole) {
    'admin'  => 'full',
    'editor' => 'limited',
    default  => 'none',
};

I personally find match much cleaner. No more forgetting a break; statement and accidentally falling through into the next case.

Why is everyone telling me to use foreach instead of a regular for loop?

In other languages, you're used to the for ($i = 0; $i < count($arr); $i++) pattern. In PHP, that's mostly a waste of your time unless you specifically need the index number for some mathematical reason. Since PHP arrays are actually ordered maps, they don't always have sequential numeric keys.

foreach is just more honest about what you're doing: you're visiting every item in a collection. It's cleaner, and you can't accidentally create an infinite loop or go "out of bounds."

$cart = [
    'Laptop' => 1200,
    'Mouse'  => 25,
    'Keyboard' => 75
];

foreach ($cart as $item => $price) {
    echo "The $item costs $$price\n";
}

See how I grabbed both the key (the product name) and the value (the price) in one line? Trying to do that with a standard for loop in PHP is a nightmare.

What's the deal with "truthy" values? Do I always need to use === true?

You'll see a lot of PHP code that just says if ($variable) instead of if ($variable === true). This is because PHP has a concept of "truthiness." Basically, PHP will try to cast whatever you put in there to a boolean.

Most things are true, but there are a few "falsy" values you have to memorize: false, 0, 0.0, an empty string "", null, and an empty array []. I'll admit, this can be dangerous. If you're checking if a user entered "0" in a form, if (!$input) will trigger because 0 is falsy, even though the user actually provided a value.

My rule of thumb: if you're checking a boolean flag, if ($isActive) is fine. If you're checking data that could be a number or a string, always use strict comparison (===) to avoid those weird PHP type-juggling surprises.




📋 Practical Task

Build a Tiered Discount Calculator

You need to write a script that calculates the final price of a shopping cart based on a user's membership tier. Use the following requirements:

  • Create an associative array called $cart where keys are item names and values are prices.
  • Create a variable $userTier which can be 'Gold', 'Silver', 'Bronze', or 'Guest'.
  • Use a match expression to determine the discount percentage:
    • Gold: 20%
    • Silver: 10%
    • Bronze: 5%
    • Guest: 0%
  • Use a foreach loop to sum up the total of all items in the cart.
  • Calculate the final total after applying the discount and print a message like: "Your total after the Gold discount is $X.XX".
Rating
0 0

There are no comments for now.

to be the first to leave a comment.