Foundations
Conditionals
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
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";
$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
$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
$temperature ← 90, $status ← (empty)
1<?php2$temperature→ 90 = 90;3$status→ (empty) = "";$status ← warm
5if ($temperature90 >= 80) {6 $status→ warm = "warm";7} else {echo "temperature=" . $temperature . " ";
11echo "temperature=" . $temperature90 . "\n";12echo "status=" . $statuswarm . "\n";outputtemperature=90 status=warm
Follow the Branch
$temperaturestarts at72.$statusstarts as an empty string.- PHP checks whether
$temperature >= 80. 72is below80, so theelsebranch sets$statustocomfortable.- The program prints
temperature=72andstatus=comfortable. | temperature | check | status | | --- | --- | --- | | 55 |55 >= 80is false | comfortable | | 72 |72 >= 80is false | comfortable | | 90 |90 >= 80is true | warm |
Exercise: conditionals.php
Reproduce status=comfortable for temperature 72, then try 55 and 90 and predict the branch result.