if, else and elseif
An if statement runs a block of code only when its condition is true: if ($books >= 10) { … }. Add else for the case when it is false. With elseif you test several conditions in order. PHP checks them from the top and runs only the first branch whose condition is true; the rest are skipped, even if they would also be true. So the order matters: test the largest limit first. The one-line form is written $y = ($x == 1) ? "One" : "Two"; it means: if $x is 1 then $y gets One, else it gets Two. It suits short choices of a value. Use curly brackets for every branch, and remember that in the condition you compare with == and never assign with =. Trace the program by writing, line by line, the value of each variable and which branch ran.
1<?php 2$books = 7; 3if ($books >= 10) { 4 $level = "gold"; 5} elseif ($books >= 5) { 6 $level = "silver"; 7} else { 8 $level = "starter"; 9} 10echo "Mona is a $level reader."; 11?>
Mona is a silver reader.
1<?php 2$books = 12; 3if ($books >= 10) { 4 $level = "gold"; 5} elseif ($books >= 5) { 6 $level = "silver"; 7} else { 8 $level = "starter"; 9} 10echo "Hana is a $level reader."; 11?>
Hana is a gold reader.
1<?php 2$x = 2; 3$y = ($x == 1) ? "One" : "Two"; 4echo $y; 5?>
Two
Write on paper an if / elseif / else for a school mark: 90 or more is “excellent”, 75 or more is “good”, 50 or more is “pass”, else “try again”. Trace it for the marks 90, 75, 74 and 49. Say why the order of the tests matters.