Learn PHP ยท 3/14

Control Structures: Guiding Your Program's Flow

11 min read

Control Structures: Guiding Your Program's Flow ๐Ÿงญ

Welcome to the fascinating world of PHP's control structures! Think of yourself as a traffic controller for your program's data. Without you, it would be chaos! Control structures are the traffic lights and signs that direct the flow of your code, telling it when to go, when to stop, and when to take a detour.

At its core, a program is a series of instructions. But what if you only want to run some instructions under certain conditions? Or what if you need to repeat a set of instructions multiple times? This is the problem that control structures solve. They give you the power to make your program smart and dynamic.


If/Else and Switch: Making Decisions ๐Ÿค”

Imagine you're building a simple login system. You need to check if the user's password is correct. If it is, you let them in. If not, you show an error message. This is a classic "decision-making" problem, and if/else statements are your go-to tool.

The if Statement: Your Basic Decision Maker

The if statement is the simplest control structure. It executes a block of code only if a specified condition is true.

Syntax:

php
if (condition) {
  // Code to execute if the condition is true
}

Example: The Login System

Let's say the correct password is "supersecret".

php
$submitted_password = "supersecret";
$correct_password = "supersecret";

if ($submitted_password == $correct_password) {
  echo "Welcome! You are now logged in. ๐ŸŽ‰";
}

In this example, since $submitted_password is indeed equal to $correct_password, the message "Welcome! You are now logged in. ๐ŸŽ‰" will be displayed.

The else Statement: The "Otherwise" Clause

But what if the password is wrong? The if statement alone doesn't handle this. That's where the else statement comes in. It provides an alternative block of code to execute if the if condition is false.

Syntax:

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

Example: Handling Incorrect Passwords

php
$submitted_password = "wrongpassword";
$correct_password = "supersecret";

if ($submitted_password == $correct_password) {
  echo "Welcome! You are now logged in. ๐ŸŽ‰";
} else {
  echo "Incorrect password. Please try again. ๐Ÿ˜ฅ";
}

Now, our login system can handle both correct and incorrect passwords.

The elseif Statement: For Multiple Conditions

What if you have more than two possibilities? For instance, in a grading system, you might have different grades for different score ranges. This is where elseif (or else if) comes to the rescue. It lets you chain multiple conditions together.

Example: A Simple Grading System

php
$score = 85;

if ($score >= 90) {
  echo "Your grade is A. Excellent! ๐ŸŒŸ";
} elseif ($score >= 80) {
  echo "Your grade is B. Good job! ๐Ÿ‘";
} elseif ($score >= 70) {
  echo "Your grade is C. You can do better. ๐Ÿ™‚";
} else {
  echo "Your grade is F. Please see your instructor. ๐Ÿ˜Ÿ";
}

Here, the program checks each condition in order. Since $score is 85, the first condition ($score >= 90) is false. It then moves to the elseif and checks if $score >= 80, which is true. So, it prints "Your grade is B. Good job! ๐Ÿ‘" and skips the rest of the conditions.

โœจ Fun Fact: The if statement is one of the oldest and most fundamental concepts in programming, existing in some form in almost every programming language ever created!

The switch Statement: An Alternative for Multiple ifs

Sometimes, you might find yourself writing a long chain of if/elseif/else statements that all check the value of the same variable. This can get a bit messy. The switch statement provides a cleaner way to handle this.

The Problem: Imagine you're building a system that gives a different message based on the day of the week.

php
$day = "Wednesday";

if ($day == "Monday") {
    echo "Time to start the week!";
} elseif ($day == "Tuesday") {
    echo "Taco Tuesday!";
} elseif ($day == "Wednesday") {
    echo "Hump day!";
} // ... and so on for the rest of the week

This works, but it's a bit repetitive.

The switch Solution:

The switch statement compares a variable against multiple possible values (called cases).

Syntax:

php
switch (variable) {
  case value1:
    // Code to execute if variable == value1
    break;
  case value2:
    // Code to execute if variable == value2
    break;
  default:
    // Code to execute if variable doesn't match any case
}

Example: Days of the Week with switch

php
$day = "Wednesday";

switch ($day) {
  case "Monday":
    echo "Time to start the week! ๐Ÿš€";
    break;
  case "Tuesday":
    echo "Taco Tuesday! ๐ŸŒฎ";
    break;
  case "Wednesday":
    echo "Hump day! ๐Ÿช";
    break;
  case "Thursday":
    echo "Almost there...";
    break;
  case "Friday":
    echo "TGIF! ๐ŸŽ‰";
    break;
  default:
    echo "Enjoy the weekend! ๐Ÿฅณ";
}

This is much neater! The break keyword is crucial. It tells PHP to exit the switch statement after a matching case is found. Without it, the code would continue to execute the code in the following cases (a behavior called "fall-through"), which is usually not what you want.


Match Expression: Modern and Clean Branching (PHP 8+) โœจ

PHP 8 introduced a new and powerful control structure called the match expression. It's like a smarter, more concise version of the switch statement.

The Problem with switch:

The switch statement is useful, but it has some quirks. You have to remember to use break, and it uses loose comparison (==), which can sometimes lead to unexpected results.

The match Solution:

The match expression is more strict and readable.

Key Differences from switch:

  • Strict Comparison: match uses strict comparison (===), meaning the value and the type must match.
  • It's an Expression: A match expression returns a value, which you can assign to a variable.
  • No break Needed: There's no "fall-through" behavior, so you don't need to use break.
  • Requires a default or All Cases: A match expression must be exhaustive. If the value doesn't match any of the arms, and there's no default arm, it will throw an error.

Syntax:

php
$result = match (variable) {
  value1 => expression1,
  value2 => expression2,
  default => default_expression,
};

Example: A Modern Day-of-the-Week Greeting

php
$day = "Wednesday";

$greeting = match ($day) {
  "Monday" => "Time to start the week! ๐Ÿš€",
  "Tuesday" => "Taco Tuesday! ๐ŸŒฎ",
  "Wednesday" => "Hump day! ๐Ÿช",
  "Thursday" => "Almost there...",
  "Friday" => "TGIF! ๐ŸŽ‰",
  default => "Enjoy the weekend! ๐Ÿฅณ",
};

echo $greeting;

Notice how much cleaner this is! The match expression directly returns the appropriate greeting, which we then store in the $greeting variable.

Combining Conditions: You can also combine multiple conditions in a single arm:

php
$statusCode = 200;

$message = match ($statusCode) {
  200, 201 => "Success!",
  404 => "Not Found.",
  500 => "Server Error.",
  default => "Unknown status.",
};

echo $message; // Outputs "Success!"

The match expression is a fantastic addition to PHP and is the preferred way to handle multi-conditional logic in modern PHP applications.


While and Do-While Loops: Repeating Actions ๐Ÿ”„

Sometimes, you need to perform the same action over and over again. For example, you might want to display a list of blog posts or process all the items in a shopping cart. This is where loops come in.

The Problem: Imagine you need to print the numbers from 1 to 5. You could do this:

php
echo 1;
echo 2;
echo 3;
echo 4;
echo 5;

This is fine for 5 numbers, but what if you need to print up to 100 or 1,000? That would be a lot of repetitive code!

The while Loop: Repeat as Long as a Condition is True

The while loop is the simplest type of loop. It repeats a block of code as long as a specified condition is true.

Syntax:

php
while (condition) {
  // Code to execute repeatedly
}

The while Loop Solution:

php
$counter = 1;

while ($counter <= 5) {
  echo $counter . "<br>";
  $counter++; // This is important! It increments the counter.
}

How it works:

  1. PHP first checks the condition ($counter <= 5). Initially, $counter is 1, so the condition is true.
  2. The code inside the loop is executed (it prints the value of $counter).
  3. $counter++ increments the value of $counter by 1.
  4. The loop goes back to step 1 and checks the condition again.
  5. This process repeats until $counter becomes 6, at which point the condition is false, and the loop terminates.

โš ๏ธ Warning: Be careful with while loops! If the condition never becomes false, you'll create an "infinite loop," which can crash your program. Always make sure there's something inside the loop that will eventually make the condition false.

The do-while Loop: Do it at Least Once

The do-while loop is very similar to the while loop, with one key difference: the condition is checked at the end of each iteration, not the beginning. This means the code inside a do-while loop is guaranteed to execute at least once.

Syntax:

php
do {
  // Code to execute
} while (condition);

Example: A Simple Menu

A do-while loop can be useful for things like command-line menus where you always want to display the options at least once.

php
$playAgain = false;

do {
  // In a real application, you'd get user input here.
  echo "Playing the game...\n";

  // For this example, we'll just set it to false to avoid an infinite loop.
  // In a real scenario, you might ask the user "Play again? (yes/no)".
  // $userInput = readline("Play again? (y/n): ");
  // $playAgain = ($userInput === 'y');

} while ($playAgain);

echo "Thanks for playing!";

In this case, "Playing the game..." will be printed once, and then the condition $playAgain (which is false) is checked, and the loop terminates.


For and Foreach Loops: Iterating Like a Pro ๐Ÿƒโ€โ™€๏ธ

While while loops are great, there are more specialized loops for common tasks.

The for Loop: The Counter's Best Friend

The for loop is ideal when you know exactly how many times you want to repeat a block of code.

The Problem: Printing numbers from 1 to 5, which we solved with a while loop, is a classic use case for a for loop.

The for Loop Solution:

php
for ($counter = 1; $counter <= 5; $counter++) {
  echo $counter . "<br>";
}

The for loop has three parts in its parentheses, separated by semicolons:

  1. Initialization: $counter = 1 is executed once at the very beginning of the loop.
  2. Condition: $counter <= 5 is checked at the beginning of each iteration. If it's true, the loop continues. If it's false, the loop ends.
  3. Increment/Decrement: $counter++ is executed at the end of each iteration.

The for loop packs all the loop control logic into one line, making it very concise for counter-based repetition.

The foreach Loop: The Array's Companion

The foreach loop is specifically designed for iterating over arrays and objects. It's the easiest and most common way to work with each element in an array.

The Problem: You have an array of your favorite movies, and you want to display them in a list.

php
$movies = ["The Matrix", "Inception", "The Dark Knight"];

You could use a for loop, but you'd need to know the size of the array and access each element by its index.

The foreach Loop Solution:

php
$movies = ["The Matrix", "Inception", "The Dark Knight"];

echo "<ul>";
foreach ($movies as $movie) {
  echo "<li>" . $movie . "</li>";
}
echo "</ul>";

How it works:

The foreach loop iterates through the $movies array. In each iteration, it takes the current element's value and assigns it to the $movie variable. This is incredibly readable and less error-prone than using a for loop for arrays.

Accessing Keys and Values:

Sometimes you need both the key and the value of an array element. foreach can do that too!

php
$movie_ratings = [
  "The Matrix" => 9,
  "Inception" => 9.5,
  "The Dark Knight" => 10
];

foreach ($movie_ratings as $movie => $rating) {
  echo "The movie '{$movie}' has a rating of {$rating}/10.<br>";
}

The foreach loop is a true workhorse in PHP, and you'll find yourself using it all the time when dealing with data.


๐Ÿ“š Further Reading and References

Challenge

Product Data Processor

Your task is to create a PHP function named processProducts that takes an array of product associative arrays as its only argument. The function must process this data and return a new array with additional information.

Each product in the input array will have the following keys: name (string), category (string), price (float), and stock (integer).

Your function must perform the following actions for each product:

  1. Calculate Discounted Price: Use a match expression to determine a discount percentage based on the category.

    • 'electronics': 10% discount
    • 'books': 5% discount
    • 'clothing': 15% discount
    • Any other category: 0% discount
      Calculate the new price and add it to the product data with the key discounted_price.
  2. Determine Stock Status: Use an if/elseif/else structure to determine the stock availability.

    • If stock is 0, the status is 'Out of Stock'.
    • If stock is between 1 and 10 (inclusive), the status is 'Low Stock'.
    • If stock is greater than 10, the status is 'In Stock'.
      Add this status to the product data with the key stock_status.
  3. Prime Stock Alert: For products with a 'Low Stock' status, you must check if the stock quantity is a prime number. To do this, implement a check using a for loop. If the stock number is prime, add a new key is_prime_stock with a boolean value of true to the product data.

Finally, return the new array of processed products. The main iteration over the input array should be handled by a foreach loop.

Expected result

Your code should contain a single function processProducts.

When this function is called with an array of product data, it must return a new array where each element is an associative array representing a product.

Each returned product array must include:

  • All the original keys (name, category, price, stock).
  • A discounted_price key with the correctly calculated price after applying the category-specific discount.
  • A stock_status key with the correct string ('Out of Stock', 'Low Stock', or 'In Stock').
  • An is_prime_stock key with the value true only if the product's status is 'Low Stock' and its stock quantity is a prime number. This key should not be present otherwise.
php

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.