Making decisions

Compare values and run different code depending on the answer.

Your PHP code runs inside your browser tab. Nothing to install.

Comparing values

A comparison asks a yes or no question.

> means greater than and < means less than. >= and <= also accept equal values.

Use == to ask whether two values are the same and != to ask whether they differ. A single = stores a value. var_export is used here to show the answer as the word true or false.

Example
<?php
$marks = 82;
echo var_export($marks > 50, true), "\n";
echo var_export($marks == 100, true), "\n";
echo var_export($marks != 0, true), "\n";

if and else

if runs a block of code only when its condition is true.

The condition goes in round brackets and each block goes between curly brackets.

else gives a second block that runs when the condition is false.

Example
<?php
$marks = 82;
if ($marks >= 40) {
    echo "Pass\n";
} else {
    echo "Fail\n";
}

Your turn: one decision

A temperature reading is stored in a variable.

Practice task

Set a variable `$temperature` to 34. Print Hot if it is above 30, otherwise print Mild.

Your answer is run and checked in the lesson. Create a free account to try it.

More than two cases

elseif adds another condition to check when the ones before it were false. You can chain as many as you need.

The conditions are checked from the top. The first one that is true runs, and the rest are skipped.

Example
<?php
$marks = 67;
if ($marks >= 75) {
    echo "Distinction\n";
} elseif ($marks >= 40) {
    echo "Pass\n";
} else {
    echo "Fail\n";
}

Your turn: three cases

Order matters when conditions overlap.

Practice task

Set `$count` to 12. Print Large if it is 50 or more, Medium if it is 10 or more, and Small otherwise.

Your answer is run and checked in the lesson. Create a free account to try it.