☰ Year plan · Communication Technology

The AND gate on a web page

Week 10 · Unit 2 Topic 3: AND gate simulation as a PHP web page: design, code and explanation, the four cases · 3 lessons
2

Reading the page’s PHP: variables, isset and &&

ICT Secondary 3 Term 1, Unit 2, Topic 3: pp. 32–39
GoalRead the PHP of the AND page: its variables, isset and the && test.
New words
variable · a named place that holds a value, written with a dollar signcondition · a test that is true or false, such as $choice1 == "on"&& · PHP’s AND: true only when both sides are true== and = · == compares two values; a single = stores a value
Explanation

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.

PartWhat it does
1three variables with start values: the lamp unlit, both choices off
2isset: do the rest only if Apply was pressed
3copy the two chosen values from $_POST
4if both are on (&&), the lamp is lit, else unlit
Worked examples
Php
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?>
The whole block. If Apply was never pressed, the start values stay, and the lamp is unlit.
VariableAt the startAfter on, on, Apply
$lampunlitlit
$choice1offon
$choice2offon
What each variable holds at the start and after the visitor chooses on in both lists and presses Apply.
Php
1var_dump(true && true);
2var_dump(true && false);
3var_dump("on" == "on");
4var_dump("ON" == "on");
Output
bool(true)
bool(false)
bool(true)
bool(false)
The signs && and == on their own. Notice that the capital letters in ON make the text different from on.
Class activity

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.

Practice
1
What does isset($_POST['apply']) check?
2
What does && mean in PHP?
3
What is the difference between = and ==?
4
What happens to $lamp if Apply is not pressed?