Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / PHP

SplFixedArray::offsetSet — Write a value at an index

Write or replace a value in a fixed-size array. Compare the direct method call with bracket assignment and distinguish the two kinds of index errors in PHP 8.3.

Version: PHP 8.3

Syntax

$array->offsetSet($index, $value);
$array[$index] = $value;

SplFixedArray::offsetSet writes to an existing slot in a \SplFixedArray object, an SPL class in the global namespace. SPL is part of PHP core and is always enabled in standard PHP 8.3 builds. $array->offsetSet($index, $value) and $array[$index] = $value write to the same slot when given a valid integer index. The value can be of any type (mixed), including null. The method changes the object and returns no value (void).

A valid index satisfies 0 <= $index && $index < $array->getSize(). With size 2, you can write at 0 or 1, but not at 2. Writing does not resize the array, and $array[] = $value does not append as it does with an ordinary PHP array. To add slots, call setSize() first and then write to an explicit index.

In PHP 8.3, an out-of-range integer index throws RuntimeException, while an invalid key such as 'label' throws TypeError. Starting in PHP 8.4, the specific exception class for an out-of-range index is OutOfBoundsException, a subclass of RuntimeException. If the index comes from external input, check is_int($index) and the bounds rather than relying on implicit conversion.

Examples

<?php
$array = new \SplFixedArray(2);

$array->offsetSet(1, 'draft');
echo $array[1], "\n";

$array[1] = 'ready';
echo $array[1], "\n";

try {
    $array->offsetSet(2, 'extra');
} catch (\RuntimeException $error) {
    echo get_class($error), "\n";
}

try {
    $array['label'] = 'extra';
} catch (\TypeError $error) {
    echo get_class($error), "\n";
}

Result

draft
ready
RuntimeException
TypeError

The script uses the method to store `draft` at index 1, then uses bracket assignment to replace it with `ready`. It finally prints the exception class names for index 2 and the key `'label'`, respectively.

Related lessons

  • PHP · Lesson 66 · Advanced · Version: 2

Sources