Lesson contents

PHP — Validating input with nullable types

A PHP function with a nullable integer result can return an accepted seat number or null. Validate the full input and its permitted range before returning the integer.

A simple example

Turn text into a number

  1. Start with "2"
  2. Do this Read an integer, add 1
  3. Result 3
The conversion produces the number 2. Adding one now gives 3.
lesson.php
<?php
$n = filter_var("2", FILTER_VALIDATE_INT);
if ($n !== false) {
    echo $n + 1, PHP_EOL;
}
Output
3
Advertisements

Validate a seat number

The regular expression checks the complete token. A nullable int result distinguishes an invalid seat from an accepted value. The caller uses the null coalescing operator to choose the fallback.

Seat 3: Accept. Seat 0: Out of range. Seat x: Invalid number.
Validate a seat request

A minibus has seats numbered 1 to 8. A passenger entering 3 can be assigned that seat. Zero is numeric but outside the seating plan, and x cannot be read as a whole seat number.

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);

function seatNumber(string $text): ?int
{
    if (!preg_match('/^[0-9]+\z/', $text)) {
        return null;
    }
    $number = (int) $text;
    return $number >= 1 && $number <= 8 ? $number : null;
}

foreach (['3', '0', 'x'] as $text) {
    echo seatNumber($text) ?? 'invalid', PHP_EOL;
}
Output
3
invalid
invalid

Only whole-number seat labels from 1 through 8 are accepted. The text 3 passes both checks. Zero parses but is outside the range. The letter x does not represent a decimal seat number.

Try it yourself

Predict the results for 8, 9, and an empty string.

Check your answer

Only 8 is accepted. Nine is outside the range and an empty string has no digits. The existing loop can continue after either rejection.

PHP language reference

Related tags

  • PHP
  • validation
  • errors
  • optional values