CKTIS / PHP
SplFixedArray::offsetGet — read an element by index
Read a fixed-array slot with `offsetGet()` or `[]`, and distinguish a `null` value from an out-of-range index or an unsupported index type.
Version: PHP 8.3
Syntax
$value = $array->offsetGet($index);
$value = $array[$index];SplFixedArray::offsetGet is an instance method that returns the value at the requested index. The result is mixed, so it retains the type of the stored value. Through ArrayAccess, an ordinary read with $array[$index] gives the same result as $array->offsetGet($index). The class belongs to SPL, which is built into PHP 8.3 and cannot be disabled. Inside a named namespace, use \SplFixedArray or import SplFixedArray.
Indices start at zero and must satisfy 0 <= $index && $index < $array->getSize(). Reading a valid slot that has never been assigned returns null. Reading an explicitly stored null gives the same result. The return value alone cannot tell those cases apart.
In PHP 8.3, an out-of-range integer index throws RuntimeException; an unsupported index type, such as the string 'name', throws TypeError. Starting with PHP 8.4, the bounds error is OutOfBoundsException, a subclass of RuntimeException. Before PHP 8.1, unsupported keys threw RuntimeException. Validate the type and range of indices from external input rather than relying on implicit conversion: for example, a [] read can treat the string '0' as index 0.
The method does not return a reference to the slot. To change a nested PHP array, read it into a variable, modify it, and write it back with $array[$index] = $value or $array->offsetSet($index, $value).
Examples
<?php
$array = new \SplFixedArray(2);
$array[0] = 42;
var_dump($array->offsetGet(0));
var_dump($array[0]);
var_dump($array->offsetGet(1));
foreach ([2, 'name'] as $index) {
try {
$array->offsetGet($index);
} catch (\RuntimeException | \TypeError $error) {
echo get_class($error), "\n";
}
}
Result
int(42) int(42) NULL RuntimeException TypeError
Both read forms return `int(42)`. The unassigned slot yields `NULL`, and the last two lines show the exception classes expected on PHP 8.3.
Related lessons
- PHP · Lesson 66 · Advanced · Version: 2