Comparing and combining conditions
A condition is a question whose answer is true or false. Comparison operators ask it: == equal, != not equal, > greater, >= greater or equal, < smaller, <= smaller or equal. Do not mix up = and ==: a single = assigns, and a double == compares. The sign === compares the value and the type, so "5" == 5 is true but "5" === 5 is false. Logical operators combine conditions. && means and: both must be true. || means or: at least one must be true. ! means not: it flips true and false. The truth table below lists every case for two values X and Y. The words and and or also exist, but they bind more loosely than =, so $t = true and false gives $t the value true, which surprises people; use && and ||. The most frequent mistake in conditions is the boundary: “5 books or more” is >= 5, while > 5 leaves out exactly 5.
| X | Y | X∨Y | X∧Y | ¬X |
|---|---|---|---|---|
| 1 | 1 | 1 | 1 | 0 |
| 1 | 0 | 1 | 0 | 0 |
| 0 | 1 | 1 | 0 | 1 |
| 0 | 0 | 0 | 0 | 1 |
1<?php 2$books = 5; 3var_dump($books >= 5, $books > 5); 4?>
bool(true) bool(false)
1<?php 2var_dump("5" == 5, "5" === 5); 3?>
bool(true) bool(false)
1<?php 2var_dump(true || false, true && false, !true); 3$t = true and false; 4var_dump($t); 5$u = (true && false); 6var_dump($u); 7?>
bool(true) bool(false) bool(false) bool(true) bool(false)
A pool lets a child in free if he is under 6 or over 65. On paper write the condition with ||, then test it with the ages 6, 7, 65 and 66, and write true or false for each. Say why the boundary values matter.