PHP — Branching with if and elseif
PHP evaluates an if and elseif chain in order. An === comparison checks both the type and the value, so the integer zero can be handled explicitly.
A simple example
Follow one branch
- Start with n is 2
- Do this Is n positive?
- Result yes
<?php
$n = 2;
if ($n > 0) {
echo "yes", PHP_EOL;
} else {
echo "no", PHP_EOL;
}
yes
Classify a stock level
Strict equality checks both type and value. elseif handles a positive low-stock count after the zero case. This example expects an integer stock count.
A student shop has three sketchbooks left. Empty stock gets a sold-out notice. A positive count of five or fewer gets a reorder notice, so three tells the shopkeeper to order soon.
Run the example
PHP 8 or later. Run these commands from the directory containing the example.
php lesson.php
<?php
declare(strict_types=1);
$stock = 3;
if ($stock === 0) {
$status = 'sold out';
} elseif ($stock <= 5) {
$status = 'order soon';
} else {
$status = 'in stock';
}
echo $status, PHP_EOL;
order soon
The stock count is 3. It passes the low-stock test after failing the zero test, so the program selects “order soon”. Zero belongs to both ranges and must be handled first.
Try it yourself
Try the boundary values 0, 5, and 6.
Check your answer
They produce “sold out”, “order soon”, and “in stock”, respectively. In a real inventory system, reject negative input before this classification.