Lesson 2 of 8 · 8 min

Decisions with if and match

<?php
$temperature = 31;

if ($temperature > 30) {
    echo "Hot\n";
} elseif ($temperature > 20) {
    echo "Warm\n";
} else {
    echo "Cool\n";
}

Comparing: == and ===

PHP has two kinds of equality:

  • === is strict: same value and same type. 5 === "5" is false.
  • == converts types first, which leads to surprises.

Use === and !== unless you have a reason not to. Other comparisons: <, >, <=, >=. Combine with && (and), || (or), ! (not).

match (PHP 8)

match picks a value by comparing strictly against a list of options:

$label = match ($status) {
    "paid" => "Thank you!",
    "pending", "processing" => "Almost there",
    default => "Unknown status",
};

It is an expression: it gives back a value you can store or return. Several options can share an arm (separated by commas), and default handles everything else.

Functions, briefly

The checks call your code as functions, written like this (the next lessons cover functions fully):

function double($n) {
    return $n * 2;
}

Your task

  1. shippingCost($kg): 5 for up to 1 kg, 10 for up to 5 kg, 20 above that.
  2. dayType($day): "weekend" for "Sat" and "Sun", otherwise "weekday", using match.
index.php
<?php
function shippingCost($kg) {
}

function dayType($day) {
}

echo shippingCost(3), "\n";
echo dayType("Sat"), "\n";

PHP 8.4 runs right here in your browser. The first run downloads about 12 MB; after that it is instant.

Discussion

Stuck? Ask here. Be kind, and share hints rather than full answers.

Loading the discussion…