PHP Lesson 14 – Control Structures

Last updated on November 29th, 2023

What types of control structures are there in PHP?

There are 4 main types of control structures in PHP:

1. If Statements
An if statement is used to make a decision in your code.
It allows you to execute a block of code only if a certain condition is met.
If the condition is true, the code inside the if statement is executed; otherwise, it’s skipped. The syntax of the if statement is as follows:

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

It checks whether the specified condition is true and executes the code block inside the curly braces if the condition is met.

2. Switch Statements
A switch statement is another way to make decisions in PHP.
It’s especially useful when you have multiple conditions to check.
You provide a variable or expression to be tested against various cases, and depending on which case matches, a specific block of code is executed. The syntax of the switch statement is as follows:

switch (variable) {
case value1:
// Code to execute if variable equals value1
break;
case value2:
// Code to execute if variable equals value2
break;
// More cases as needed
default:
// Code to execute if none of the cases match
}

It evaluates the variable and compares it to various case values. When it finds a match, the corresponding code block is executed. The break statement is used to exit the switch block.

3. Loops
Loops are used to repeat a block of code multiple times until a certain condition is met.

There are three main types of loops in PHP:

A. For Loop: Used for a specific number of iterations. For Loop syntax is:

for (initialization; condition; increment/decrement) {
// Code to execute in each iteration
}

B. While Loop: Repeats as long as a condition is true. While Loop syntax is:

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

C. Foreach Loop: Specifically designed for iterating over arrays or other iterable data types. The foreach loop is especially useful when working with arrays of unknown length or when you want to perform the same operation on each element of an array without having to worry about array indexes. It simplifies the code and makes it more readable compared to traditional for loops when dealing with arrays. Foreach Loop syntax is:

foreach ($array as $value) {
// Code to execute for each value in the array
}

4. Conditional Operator (Ternary Operator)
The conditional operator, often called the ternary operator, is a shorthand way of writing if-else statements.
It’s used to assign a value to a variable based on a condition.
It’s concise and can make your code more readable when dealing with simple conditions.
Conditional Operator syntax is:

$variable = (condition) ? value_if_true : value_if_false;

It assigns the value of value_if_true to $variable if the condition is true; otherwise, it assigns the value of value_if_false.

Examples of PHP control structures:

1. If Statement:

<?php
  $age = 25;  // We're defining a variable called $age and setting it to 25.

  if ($age >= 18) {
    echo "You are an adult.";
  } else {
    echo "You are not yet an adult.";
  }
?>

We start by creating a variable called $age and assign it the value 25. This variable represents a person’s age.
Next, we have an if statement. An if statement is like a decision point in your code. It checks whether a certain condition is true or false. In this case, we’re checking if the value of $age is greater than or equal to 18.
The condition inside the if statement is $age >= 18. The >= is a comparison operator that checks if the left side (in this case, $age) is greater than or equal to the right side (18).
If the condition is true (which means that the age is 18 or older), it executes the code inside the curly braces {} following the if. It prints out “You are an adult.”
If the condition is false (which means that the age is less than 18), it executes the code inside the else block. It prints out “You are not yet an adult.”
So, when you run this PHP code with $age set to 25, it will output “You are an adult.” This is because 25 is greater than or equal to 18, so the if block is executed. If you were to change the value of $age to, say, 15, it would output “You are not yet an adult” because 15 is less than 18, and the else block would be executed.

2. Switch Statement:

<?php
  $dayOfWeek = "Monday";

  switch ($dayOfWeek) {
    case "Monday":
      echo "It's the start of the week.";
      break;
    case "Wednesday":
      echo "It's midweek.";
      break;
    case "Friday":
      echo "It's almost the weekend.";
      break;
    default:
      echo "It's just another day.";
  }
?>

We start by creating a variable called $dayOfWeek and assign it the value “Monday”. So this variable contains as a value a specific day of the week.
Next, we have a switch statement. A switch statement is like a series of if-else conditions but organized in a more structured way. It checks the value of $dayOfWeek against different cases.
Inside the switch statement, we have several case sections. Each case represents a possible value of $dayOfWeek. In this code, we have cases for “Monday,” “Wednesday,” and “Friday.”
If the value of $dayOfWeek matches one of the cases, the code inside that case is executed. For example, if $dayOfWeek is “Monday,” it will execute the code in the “Monday” case, which is echo “It’s the start of the week.”;
The break statement is used after each case. It tells PHP to exit the switch statement once the code inside a matching case is executed. This prevents the code from continuing to execute other cases after a match is found.
If $dayOfWeek doesn’t match any of the defined cases, the default case is executed. In this code, the default case echo “It’s just another day.”; will be executed if $dayOfWeek is something other than “Monday,” “Wednesday,” or “Friday.”
So, when you run this PHP code with $dayOfWeek set to “Monday,” it will output “It’s the start of the week.” If you change the value of $dayOfWeek to “Wednesday” or “Friday,” it will output the corresponding message. If you set it to any other value, it will output “It’s just another day.”

3. While Loop:

<?php
  $count = 1;

  while ($count <= 5) {
    echo "Count: $count<br>";
    $count++;
  }
?>

In the above code we start by creating a variable called $count and assign it the value 1. This variable will be used to keep track of our counting.
Next, we have a while loop. A while loop is a control structure in PHP that repeatedly executes a block of code as long as a specified condition is true.
The condition inside the while loop is $count <= 5. This means that as long as the value of $count is less than or equal to 5, the code inside the loop will be executed.
Inside the while loop, we have an echo statement. It prints the current value of $count along with the text “Count:” to the web page. The <br> tag is used to add a line break, so each count appears on a new line.
After printing the current value of $count which is 1, we have $count++. This is an increment operation that adds 1 to the current value of $count. So, in each iteration of the loop, the value of $count is increased by 1.
The loop continues to execute as long as the condition $count <= 5 is true. Once $count becomes greater than 5, the condition becomes false, and the loop stops executing.
So, when you run this PHP code, it will produce the following output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

It counts from 1 to 5, printing each count on a new line, and then the loop stops because the condition is no longer true when $count becomes 6.

For example, if you want the code to display the numbers from 1 to 100, you need to change it like this:

<?php
  $count = 1;

  while ($count <= 100) {
    echo "Count: $count<br>";
    $count++;
  }
?>

4. For Loop:

<?php
  for ($i = 1; $i <= 4; $i++) {
    echo "Iteration $i<br>";
  }
?>

A for loop is a control structure in PHP that is used to execute a block of code a specific number of times.
Inside the parentheses of the for loop, we have three parts separated by semicolons:

$i = 1: This is the initialization part. Here, we’re creating a variable called $i and setting its initial value to 1. The variable $i is commonly used as a loop counter.
$i <= 4: This is the condition part. The loop will continue executing as long as the condition is true. In this case, the loop will continue as long as $i is less than or equal to 4.
$i++: This is the increment part. After each iteration of the loop, this part is executed. It increments the value of $i by 1. It’s equivalent to writing $i = $i + 1;.

Inside the curly braces {}, we have the code that gets executed during each iteration of the loop.
The code inside the loop consists of an echo statement. It prints the current value of $i along with the text “Iteration” to the web page. The <br> tag is used to add a line break, so each iteration’s output appears on a new line.

Now, let’s see what happens when we run this code:

The for loop starts with $i equal to 1 (as specified in the initialization part). It checks if $i is less than or equal to 4 (as specified in the condition part). Since 1 is indeed less than or equal to 4, the loop executes the code inside the curly braces.
It prints “Iteration 1” to the web page and then increments the value of $i by 1 (as specified in the increment part). Now, $i becomes 2.
The loop repeats the process: It checks the condition, prints “Iteration 2,” increments $i to 3, and so on.
This continues until $i reaches 5. When $i becomes 5, the condition $i <= 4 is no longer true, and the loop stops.
So, when you run this PHP code, it will produce the following output:

Iteration 1
Iteration 2
Iteration 3
Iteration 4

It iterates through the loop four times, printing each iteration number on a new line, and then the loop terminates.

5. Foreach Loop:

We already used foreach in the PHP arrays tutorial. The foreach loop in PHP is a powerful construct used for iterating through arrays and objects. It simplifies the process of looping through the elements of an array, making it easier to work with data structures.

Suppose you have an array of numbers and you want to calculate their sum using a foreach loop.

<?php
// Create an array of numbers
$numbers = array(10, 20, 30, 40, 50);

// Initialize a variable to store the sum
$sum = 0;

// Use a foreach loop to iterate through the array
foreach ($numbers as $number) {
    // Add each number to the sum
    $sum += $number;
}

// Display the sum
echo "The sum of the numbers is: " . $sum;
?>

In the above example we start by defining an array called $numbers containing five integer values: 10, 20, 30. 40 and 50.
We initialize a variable $sum to store the sum of the numbers, setting it initially to zero.
The foreach loop is used to iterate through each element of the $numbers array. In each iteration, the current value of the array element is assigned to the variable $number.
Inside the loop, we add the value of $number to the $sum variable.
After the loop has finished iterating through all the elements, we echo out the result, which is the sum of the numbers (150).

The foreach loop is especially useful when working with arrays of unknown length or when you want to perform the same operation on each element of an array without having to worry about array indexes. It simplifies the code and makes it more readable compared to traditional for loops when dealing with arrays.

6. Conditional Operator (Ternary Operator):

<?php
  $isSunny = true;

  $weatherMessage = $isSunny ? "It's sunny today." : "It's not sunny today.";

  echo $weatherMessage;
?>

The conditional (ternary) operator ? is used here to assign a value to $weatherMessage based on the value of $isSunny. It’s a compact way to handle conditional assignments.
We start by creating a variable called $isSunny and set it to true. This variable represents whether the weather is sunny or not. In this case, it’s set to true, indicating that it’s a sunny day.
Next, we have a line of code that uses a ternary conditional operator ? : to assign a value to another variable called $weatherMessage. The ternary operator is a neat way to set a variable’s value based on a condition.
The condition being checked here is $isSunny. If $isSunny is true, it evaluates the expression before the ? (which is “It’s sunny today.”) and assigns it to $weatherMessage. If $isSunny is false, it evaluates the expression after the : (which is “It’s not sunny today.”) and assigns that to $weatherMessage.
In this case, since $isSunny is true, the first expression “It’s sunny today.” is assigned to $weatherMessage. So, $weatherMessage now holds the message “It’s sunny today.”
Finally, we use the echo statement to print the value of $weatherMessage to the screen.

So, when you run this PHP code with $isSunny set to true, it will output:

It’s sunny today.

This is because the ternary operator assigns the message “It’s sunny today.” to $weatherMessage based on the true value of $isSunny. If you were to change the value of $isSunny to false and run the code again, it would output:

It’s not sunny today.

This time, the ternary operator assigns the message “It’s not sunny today.” to $weatherMessage based on the false value of $isSunny.