Reading the page’s PHP: variables, isset and &&
The PHP block at the top has four parts. Part 1 declares three variables with start values: $lamp is unlit, and $choice1 and $choice2 are off. Part 2 is the test isset($_POST['apply']), true only when Apply was pressed (remember Week 7). Part 3, inside it, copies the two chosen values from $_POST. Part 4 is the AND: if $choice1 == "on" && $choice2 == "on", then $lamp becomes lit, else unlit. The sign && is PHP’s AND for conditions. It is true only when both sides are true, exactly as in the truth table of Week 8. Take care with the signs: == compares two values and gives true or false, while a single = stores a value. Writing = inside an if is a classic slip. At the end the page prints $lamp with echo.
| Part | What it does |
|---|---|
| 1 | three variables with start values: the lamp unlit, both choices off |
| 2 | isset: do the rest only if Apply was pressed |
| 3 | copy the two chosen values from $_POST |
| 4 | if both are on (&&), the lamp is lit, else unlit |
1<?php 2$lamp = "unlit"; 3$choice1 = "off"; 4$choice2 = "off"; 5 6if (isset($_POST['apply'])) { 7 $choice1 = $_POST['list1']; 8 $choice2 = $_POST['list2']; 9 if ($choice1 == "on" && $choice2 == "on") { 10 $lamp = "lit"; 11 } else { 12 $lamp = "unlit"; 13 } 14} 15?>
| Variable | At the start | After on, on, Apply |
|---|---|---|
| $lamp | unlit | lit |
| $choice1 | off | on |
| $choice2 | off | on |
1var_dump(true && true); 2var_dump(true && false); 3var_dump("on" == "on"); 4var_dump("ON" == "on");
bool(true) bool(false) bool(true) bool(false)
Change the test so that the lamp is lit only when the first list is on and the second list is off. Write the new test, then list the lamp for the four choices.