PHP Conditional Statements and Loop Control Basics

Topic Overview

Welcome! In this lesson, we're exploring special instructions in PHP: Conditional Statements, along with the break and continue statements. As we've learned, loops allow us to execute a block of code numerous times. By combining these loops with conditional statements and incorporating the useful break and continue instructions, we achieve more robust and efficient code. Let's dive in!

The 'if' Statement

In PHP, the if statement triggers actions in our code based on a specific condition. Consider this straightforward example, where the if statement determines which message to print based on the value of $temperature:

PHP
<?php
$temperature = 15;

if ($temperature > 20) {
    echo "Wear light clothes."; // This message will print if the temperature is over 20.
} else {
    echo "Bring a jacket."; // This message will print otherwise.
}
?>

We can evaluate multiple conditions using elseif. This phrase means, "If the previous condition isn't true, then check this one":

PHP
<?php
$temperature = 15;

if ($temperature > 30) {
    echo "It's hot outside!"; // This will print if the temperature is over 30.
} elseif ($temperature > 20) {
    echo "The weather is nice."; // This will print if the temperature is between 21 and 30.
} else {
    echo "It might be cold outside."; // This will print if the temperature is 20 or below.
}
?>

The 'break' Statement

We use the break statement whenever we want to exit a loop prematurely once a condition is met:

PHP
<?php
$numbers = [1, 3, 7, 9, 12, 15];

foreach ($numbers as $number) {
    if ($number % 2 == 0) {
        echo "The first even number is: " . $number . "\n"; // This prints the first even number.
        break; // This stops the loop after printing the first even number.
    }
    echo "Number: " . $number . "\n";
}
?>

The 'continue' Statement

The continue statement bypasses the rest of the loop code for the current iteration only:

PHP
<?php
for ($i = 0; $i < 6; $i++) {
    if ($i == 3) {
        continue; // This skips the print command for '3'.
    }
    echo $i . "\n"; // This prints the numbers from 0 to 5 except 3.
}
?>
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal