Codeskill

Learn to code, step by step

Control Structures: Making Decisions with PHP

PHP control structures. If/else, switch, and loops – so your scripts can make decisions and repeat work.

What are control structures?

Control structures decide what your code does and when. They let PHP run different code depending on a condition, or run the same code multiple times. Without them, every script would do exactly the same thing every time.

The if statement

An if statement runs a block of code only when a condition is true:

<?php
$weather = "sunny";

if ($weather == "sunny") {
    echo "It's a beautiful day!";
}
?>

The message only displays when $weather equals “sunny”.

The else statement

Use else to define what happens when the if condition is false:

<?php
$weather = "rainy";

if ($weather == "sunny") {
    echo "It's a beautiful day!";
} else {
    echo "Looks like it might rain.";
}
?>

When it is not sunny, the script prints the rain message instead.

The elseif statement

When you have more than two outcomes, chain conditions with elseif:

<?php
$weather = "cloudy";

if ($weather == "sunny") {
    echo "It's a beautiful day!";
} elseif ($weather == "rainy") {
    echo "Don't forget your umbrella!";
} else {
    echo "Could be anything, it's unpredictable!";
}
?>

The switch statement

A switch is often cleaner than a long chain of elseif statements when you are comparing one value against several options:

<?php
$weather = "windy";

switch ($weather) {
    case "sunny":
        echo "It's a beautiful day!";
        break;
    case "rainy":
        echo "Don't forget your umbrella!";
        break;
    case "windy":
        echo "Hold onto your hats!";
        break;
    default:
        echo "Could be anything, it's unpredictable!";
}
?>

The while loop

Loops repeat a block of code. A while loop keeps going as long as its condition is true:

<?php
$i = 1;

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

This prints the numbers 1 to 5.

The do...while loop

A do...while loop always runs its body at least once, then checks the condition:

<?php
$i = 0;

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

Same idea as while, but the condition is checked after each run, not before.

The for loop

Use a for loop when you know how many times you want to repeat:

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

Handy for stepping through arrays too.

The foreach loop

foreach loops through every element in an array:

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

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

Each colour in the array is printed on its own line.

Control structures are how you make PHP scripts respond to different situations. Try building a few small examples with the weather samples above, then move on to the dedicated loops page for more detail.

PreviousVariables and Data Types in PHP: A Beginner’s Guide