PHP — Ternary expressions
A PHP ternary expression can choose a display value and defer the division until the count is known to be nonzero.
A simple example
Choose one value
- Start with n is 2
- Do this Choose by sign
- Result positive
<?php
$n = 2;
echo ($n > 0 ? "positive" : "other"), PHP_EOL;
positive
Choose a report value when a sample is missing
Report a whole-number average for a nonempty group and a text label for an empty group. Guard the division where the result is selected. Use the explicit condition $count === 0. It compares both type and value, and gives a valid nonempty group its own result.
A monitor displays the average of a sensor’s samples. If no sample arrived, show a message before attempting division. Three samples with a total of 18 give an average of 6.
Run the example
Use PHP 8.2 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
foreach ([0, 3] as $count) {
$label = $count === 0 ? 'no samples' : (string) intdiv(18, $count);
echo $label . "\n";
}
no samples 6
The first group has zero samples and displays no samples. In the second group, 18 divided by 3 gives 6.
Try it yourself
What does an observed total of zero with three samples display?
Check your answer
It displays 0. This is a measured zero, whereas the empty group has no average.