Control structures

Control structures allow you to control the flow of your program, making it possible to execute certain code blocks only if certain conditions are met.

Here are some of the most common control structures in PHP:

  1. if/else statements:

The if/else statement is used to execute code if a condition is true, and another code block if the condition is false. Here's an example:

<?php
$age = 20;

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

In this example, the code will output "You are an adult." because the variable $age is greater than or equal to 18.

  1. for loops:

The for loop is used to execute a block of code a specific number of times. Here's an example:

<?php
for ($i = 0; $i < 5; $i++) {
    echo "The value of i is: " . $i . "<br>";
}
?>

In this example, the code will output the value of the variable $i five times.

  1. while loops:

The while loop is used to execute a block of code as long as a certain condition is true. Here's an example:

<?php
$x = 1;

while ($x <= 5) {
    echo "The value of x is: " . $x . "<br>";
    $x++;
}
?>

In this example, the code will output the value of the variable $x five times.

  1. switch statements:

The switch statement is used to select one of many blocks of code to be executed. Here's an example:

<?php
$color = "red";

switch ($color) {
    case "red":
        echo "Your favorite color is red.";
        break;
    case "blue":
        echo "Your favorite color is blue.";
        break;
    case "green":
        echo "Your favorite color is green.";
        break;
    default:
        echo "You did not select a favorite color.";
}
?>

In this example, the code will output "Your favorite color is red." because the variable $color is set to "red".

These are just a few examples of control structures in PHP. There are many more, but these are the most commonly used ones.

Last updated