typestar

if and elseif in PHP

Branching on a value with PHP's one-word elseif and the ternary.

<?php
$hour = 14;

// elseif is one word in PHP
if ($hour < 12) {
    $greeting = "good morning";
} elseif ($hour < 18) {
    $greeting = "good afternoon";
} else {
    $greeting = "good evening";
}

echo $greeting, PHP_EOL;
echo $hour >= 9 && $hour < 17 ? "office hours" : "closed", PHP_EOL;

How it works

  1. The chain tests $hour against noon and 18:00, binding one greeting.
  2. elseif is a single keyword in PHP, unlike the two-word forms elsewhere.
  3. A ternary with && condenses the office-hours check to one line.

Keywords and builtins used here

The run, in numbers

Lines
14
Characters to type
280
Tokens
67
Three-star pace
85 tpm

At the three-star pace of 85 tokens a minute, this run takes about 47 seconds.

Type this snippet

Step 1 of 3 in Control flow, step 4 of 27 in Language basics.

← Previous Next →

if and elseif in other languages