An if statement lets PHP choose between branches.

if statement An `if` statement runs one block when its condition is true and can use `else` for the other case.

Conditionals

temperature
conditionals.php
Replay: real traced execution (multi-file project)
<?php
$temperature = 72;
$status = "";

if ($temperature >= 80) {
    $status = "warm";
} else {
    $status = "comfortable";
}

echo "temperature=" . $temperature . "\n";
echo "status=" . $status . "\n";
<?php
$temperature = 55;
$status = "";

if ($temperature >= 80) {
    $status = "warm";
} else {
    $status = "comfortable";
}

echo "temperature=" . $temperature . "\n";
echo "status=" . $status . "\n";
<?php
$temperature = 90;
$status = "";

if ($temperature >= 80) {
    $status = "warm";
} else {
    $status = "comfortable";
}

echo "temperature=" . $temperature . "\n";
echo "status=" . $status . "\n";
  1. $temperature ← 72, $status ← (empty)

    1<?php2$temperature→ 72 = 72; //@temperature=55, 903$status→ (empty) = "";45if ($temperature >= 80) {6    $status = "warm";7} else {8    $status→ comfortable = "comfortable";9}1011echo "temperature=" . $temperature72 . "\n";12echo "status=" . $statuscomfortable . "\n";
    outputtemperature=72
    status=comfortable
  1. $temperature ← 55, $status ← (empty)

    1<?php2$temperature→ 55 = 55;3$status→ (empty) = "";45if ($temperature >= 80) {6    $status = "warm";7} else {8    $status→ comfortable = "comfortable";9}1011echo "temperature=" . $temperature55 . "\n";12echo "status=" . $statuscomfortable . "\n";
    outputtemperature=55
    status=comfortable
  1. $temperature ← 90, $status ← (empty)

    1<?php2$temperature→ 90 = 90;3$status→ (empty) = "";
  2. $status ← warm

    5if ($temperature90 >= 80) {6    $status→ warm = "warm";7} else {
  3. echo "temperature=" . $temperature . " ";

    11echo "temperature=" . $temperature90 . "\n";12echo "status=" . $statuswarm . "\n";
    outputtemperature=90
    status=warm

Follow the Branch

  1. $temperature starts at 72.
  2. $status starts as an empty string.
  3. PHP checks whether $temperature >= 80.
  4. 72 is below 80, so the else branch sets $status to comfortable.
  5. The program prints temperature=72 and status=comfortable. | temperature | check | status | | --- | --- | --- | | 55 | 55 >= 80 is false | comfortable | | 72 | 72 >= 80 is false | comfortable | | 90 | 90 >= 80 is true | warm |

Exercise: conditionals.php

Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.