Menu
Coddy logo textTech

If Statement

Part of the Fundamentals section of Coddy's PHP journey — lesson 28 of 71.

Now that you know how to create boolean expressions, it's time to use them to make your code do different things based on conditions. The if statement lets you execute code only when a condition is true.

The basic syntax wraps your condition in parentheses, followed by curly braces containing the code to run:

<?php
$age = 20;

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

When PHP encounters an if statement, it evaluates the condition. If the result is true, the code inside the curly braces runs. If it's false, PHP skips that block entirely and continues with the rest of the program.

<?php
$temperature = 35;

if ($temperature > 30) {
    echo "It's hot outside!";
}

echo " Have a nice day!";
?>

In this example, both messages appear because the condition is true. If $temperature were 25, only "Have a nice day!" would be printed since the if block would be skipped.

You can use any boolean expression as your condition, including the comparison and logical operators you've already learned.

challenge icon

Challenge

Easy

Read two integers from input: a speed and a speedLimit.

Use an if statement to check if the driver is speeding. If speed is greater than speedLimit, print Speeding ticket issued.

After the if statement (regardless of whether the condition was true or false), always print Drive safely! on a new line.

Example:

If the inputs are 75 and 60, the output should be:

Speeding ticket issued
Drive safely!

If the inputs are 55 and 60, the output should be:

Drive safely!

Cheat sheet

The if statement executes code only when a condition is true.

Basic syntax:

<?php
if ($age >= 18) {
    echo "You are an adult";
}
?>

PHP evaluates the condition in parentheses. If true, the code inside curly braces runs. If false, that block is skipped.

<?php
$temperature = 35;

if ($temperature > 30) {
    echo "It's hot outside!";
}

echo " Have a nice day!";
?>

You can use any boolean expression as the condition, including comparison and logical operators.

Try it yourself

<?php
// Read input
$speed = intval(fgets(STDIN));
$speedLimit = intval(fgets(STDIN));

// TODO: Write your code below
// Check if speed is greater than speedLimit and print appropriate messages


?>
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals