Control structures are essential for controlling the flow of your PHP code. In this lesson, we'll cover conditional statements and loops, which allow you to make decisions based on certain conditions and execute code repeatedly.

Conditional Statements

In PHP, you can use if, else, and elseif statements to perform different actions based on certain conditions.

$age = 18;

if ($age >= 18) {
  echo "You are an adult.";
} elseif ($age >= 13) {
  echo "You are a teenager.";
} else {
  echo "You are a child.";
}

Switch Statements

A switch statement can be used as an alternative to multiple if and elseif statements when you need to perform different actions based on the value of a single variable.

$day = "Monday";

switch ($day) {
  case "Monday":
    echo "Today is Monday.";
    break;
  case "Tuesday":
    echo "Today is Tuesday.";
    break;
  case "Wednesday":
    echo "Today is Wednesday.";
    break;
  default:
    echo "Invalid day.";
}

Loops

Loops allow you to execute a block of code repeatedly. PHP supports several types of loops:

  1. for loop: Runs a block of code a specified number of times.
for ($i = 1; $i <= 10; $i++) {
  echo "The number is: $i<br>";
}
  1. while loop: Runs a block of code as long as a specified condition is true.
$i = 1;

while ($i <= 10) {
  echo "The number is: $i<br>";
  $i++;
}
  1. do-while loop: Runs a block of code once, then repeats the loop as long as a specified condition is true.
$i = 1;

do {
  echo "The number is: $i<br>";
  $i++;
} while ($i <= 10);
  1. foreach loop: Iterates over an array or an object, running a block of code for each element.
$fruits = array("apple", "banana", "cherry");

foreach ($fruits as $fruit) {
  echo "The fruit is: $fruit<br>";
}

Actionable Work:

Practice using control structures in PHP by completing the following exercises:

  1. Create a PHP script that prints a message based on the current day of the week using an if statement.