OutOfBoundsException
PHPERRORCommonBounds
Value not in valid range at runtime
Quick Answer
Check index bounds before accessing elements; throw OutOfBoundsException in custom data structures for out-of-range access.
What this means
Thrown when a runtime value falls outside the acceptable bounds of a container or range. Use for index-out-of-range conditions in custom data structures.
Why it happens
- 1Accessing an index beyond the end of a custom collection
- 2Negative index in a bounded container
Fix
Bounds check in custom collection
Bounds check in custom collection
public function get(int $index): mixed {
if ($index < 0 || $index >= count($this->items)) {
throw new \OutOfBoundsException("Index $index out of bounds [0, " . count($this->items) . ")");
}
return $this->items[$index];
}Why this works
Explicit bounds check with a descriptive message makes the error actionable.
Code examples
SplFixedArray accessphp
$arr = new \SplFixedArray(5); $arr[10]; // RuntimeException (PHP throws this for SplFixedArray)
Custom throwphp
if (!isset($this->stack[$n])) {
throw new \OutOfBoundsException("Stack index $n does not exist");
}Same error in other languages
Sources
Official documentation ↗
PHP Manual
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev