Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

OutOfBoundsException

OutOfBoundsException extends RuntimeException for an invalid index or key.

Version: PHP 8.4; repository runtime, production runtime not attested

Syntax

throw new OutOfBoundsException("index missing")

OutOfBoundsException extends RuntimeException for an invalid index or key. A library or collection can throw it on a failed bounds check, whereas ordinary array access to a missing key in PHP 8.4 emits a warning and yields null. Use array_key_exists when an existing key may itself contain null. The example distinguishes that stored null from a missing index.

function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }
NULL
OutOfBoundsException index 1

Examples

<?php
function fetchRow(array $rows, int $i): mixed {
    if (!array_key_exists($i, $rows)) { throw new OutOfBoundsException("index " . $i); }
    return $rows[$i];
}
var_dump(fetchRow([null], 0));
try { fetchRow([null], 1); }
catch (OutOfBoundsException $e) { echo get_class($e), " ", $e->getMessage(); }

Result

NULL
OutOfBoundsException index 1

Sources