PHP, lesson 4
Programs need to react differently to different data: charge shipping only on small orders,
warn only when the battery is low. PHP's main tool for this is if.
The condition goes in parentheses, and the code to run goes in curly braces. Indent the block so readers can see its shape; PHP itself only cares about the braces.
PHP tests the conditions from top to bottom and runs only the first block whose condition
is true, so the second test doesn't need to repeat $speed <= 120.
| Operator | Means |
|---|---|
=== | identical: same value and same type |
!== | not identical |
== |
2 exercises to try what you just read.
| equal after type juggling |
!= | not equal after type juggling |
< > <= >= | ordering |
== converts types before comparing, so "1" == "01" and 100 == "1e2" are both true. That
can surprise you. Prefer === and !== unless you have a reason not to. (PHP 8 removed the
worst surprises; 0 == "a" is now false.)
The spaceship operator <=> returns -1, 0 or 1 depending on whether the left side
is smaller, equal or bigger. You'll use it for sorting later.
&& is true when both sides are true.|| is true when at least one side is true.! flips true and false.PHP also has and and or, but they have very low precedence and behave oddly in
assignments. Stick to && and ||.
In a condition, 0, 0.0, "", "0", null and empty arrays count as false. Everything
else counts as true.
The ternary operator picks one of two values: $label = $n % 2 === 0 ? "even" : "odd";.
The null coalescing operator ?? gives a fallback when something is null or missing:
$name = $input ?? "guest";.
match compares one value against several options and returns a result. It uses strict
=== comparison, has no fall-through, and lets you list several values in one arm:
If nothing matches and there is no default, PHP throws an UnhandledMatchError, so typos
don't slip through silently.
A handy trick is match (true): each arm is a full condition, and the first one that is
true wins. That's a tidy replacement for a long if/elseif chain that only picks a value:
Read an age (a whole number) and print the ticket price using match (true):
58712Sample input:
Sample output:
The input has two lines: player 1's move and player 2's move, each rock, paper or
scissors. Rock beats scissors, scissors beats paper, paper beats rock. Print
Player 1 wins, Player 2 wins or Draw.
Sample input:
Sample output:
<?php
$battery = (int) trim(fgets(STDIN));
if ($battery < 20) {
echo "Battery low, plug in soon.\n";
}
echo "Status checked.\n";<?php
if ($speed > 120) {
echo "Way too fast\n";
} elseif ($speed > 90) {
echo "A bit fast\n";
} else {
echo "Fine\n";
}<?php
if ($age >= 18 && $hasTicket) {
echo "Come in\n";
}<?php
$type = match ($day) {
"Sat", "Sun" => "weekend",
"Mon", "Tue", "Wed", "Thu", "Fri" => "weekday",
default => "unknown",
};<?php
$size = match (true) {
$kg < 1 => "small",
$kg < 10 => "medium",
default => "large",
};158rock
scissorsPlayer 1 wins