Values and Types
Booleans and Null
Booleans represent true-or-false answers, while null marks a missing value.
null
`null` means a variable has no useful value yet.
Booleans and Null
booleans_null.php
Replay: real traced execution (multi-file project)
<?php
$stock = 0;
$hasStock = $stock > 0;
$label = null;
if ($hasStock) {
$label = "ready";
} else {
$label = "empty";
}
echo "stock=" . $stock . "\n";
echo "hasStock=" . ($hasStock ? "true" : "false") . "\n";
echo "label=" . $label . "\n";
<?php
$stock = 2;
$hasStock = $stock > 0;
$label = null;
if ($hasStock) {
$label = "ready";
} else {
$label = "empty";
}
echo "stock=" . $stock . "\n";
echo "hasStock=" . ($hasStock ? "true" : "false") . "\n";
echo "label=" . $label . "\n";
<?php
$stock = 5;
$hasStock = $stock > 0;
$label = null;
if ($hasStock) {
$label = "ready";
} else {
$label = "empty";
}
echo "stock=" . $stock . "\n";
echo "hasStock=" . ($hasStock ? "true" : "false") . "\n";
echo "label=" . $label . "\n";
$stock ← 0, $hasStock ← (empty), $label ← NULL
1<?php2$stock→ 0 = 0; //@stock=2, 53$hasStock→ (empty) = $stock0 > 0;4$label→ NULL = null;56if ($hasStock) {7 $label = "ready";8} else {9 $label→ empty = "empty";10}1112echo "stock=" . $stock0 . "\n";13echo "hasStock=" . ($hasStock(empty) ? "true" : "false") . "\n";14echo "label=" . $labelempty . "\n";outputstock=0 hasStock=false label=empty
$stock ← 2, $hasStock ← 1, $label ← NULL
1<?php2$stock→ 2 = 2;3$hasStock→ 1 = $stock2 > 0;4$label→ NULL = null;$label ← ready
6if ($hasStock1) {7 $label→ ready = "ready";8} else {echo "stock=" . $stock . " ";
12echo "stock=" . $stock2 . "\n";13echo "hasStock=" . ($hasStock1 ? "true" : "false") . "\n";14echo "label=" . $labelready . "\n";outputstock=2 hasStock=true label=ready
$stock ← 5, $hasStock ← 1, $label ← NULL
1<?php2$stock→ 5 = 5;3$hasStock→ 1 = $stock5 > 0;4$label→ NULL = null;$label ← ready
6if ($hasStock1) {7 $label→ ready = "ready";8} else {echo "stock=" . $stock . " ";
12echo "stock=" . $stock5 . "\n";13echo "hasStock=" . ($hasStock1 ? "true" : "false") . "\n";14echo "label=" . $labelready . "\n";outputstock=5 hasStock=true label=ready
Follow the Branch
$stockstarts at0.$hasStock = $stock > 0becomesfalse.$labelstarts asnull.- Because
$hasStockis false, theelsebranch sets$labeltoempty. - The program prints
stock=0,hasStock=false, andlabel=empty. | stock | hasStock | label | | --- | --- | --- | | 0 | false | empty | | 2 | true | ready | | 5 | true | ready |
Exercise: booleans_null.php
Reproduce label=empty, then use the pinned stock values 2 and 5 to predict hasStock and label.