Control Structures

Control structures are the core of any programming language's control flow logic. They allow your program to make decisions or to repeat an operation. PHP supports several control structures, including:

If, Elseif, Else Statements

These statements are used to perform different actions based on different conditions.

<?php
$x = 10;
$y = 20;

if ($x > $y) {
    echo "x is greater than y";
} elseif ($x == $y) {
    echo "x is equal to y";
} else {
    echo "x is less than y";
}
?>

Switch Statement

The switch statement is used to perform different actions based on different conditions:

<?php
$favcolor = "blue";

switch ($favcolor) {
    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 "Your favorite color is neither red, blue, nor green!";
}
?>

While Loop

The while loop executes a block of code as long as the specified condition is true:

<?php
$x = 1;

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

For Loop

The for loop is used when you know in advance how many times the script should run:

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}
?>

Foreach Loop

The foreach loop works only on arrays, and is used to loop through each key/value pair in an array:

<?php
$colors = array("red", "green", "blue", "yellow");

foreach ($colors as $value) {
    echo "$value <br>";
}
?>

Last updated