Lesson contents

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

  1. Start with n is 2
  2. Do this Is n positive?
  3. Result yes
The condition selects the first branch. Changing the value to zero selects the other branch.
lesson.php
<?php
$n = 2;
if ($n > 0) {
    echo "yes", PHP_EOL;
} else {
    echo "no", PHP_EOL;
}
Output
yes
Advertisements

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.

On the shelf: 3 books. Low-stock limit: 5 books. Shelf notice: Order soon.
Decide when to restock

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
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;
Output
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.

PHP language reference

Related tags

  • PHP
  • conditions
  • branching
  • comparison