CKTIS / PHP
SplFixedArray
Allocate a fixed number of positions indexed from zero.
Version: PHP 8.4; repository runtime, production runtime not attested
Syntax
new SplFixedArray($size)Allocate a fixed number of positions indexed from zero. Unassigned slots contain null and count reflects the current capacity. setSize changes the capacity; shrinking discards removed positions. Access outside the allocated range raises OutOfBoundsException in PHP 8.4. The SplFixedArray::offsetSet method writes an allocated slot and SplFixedArray::offsetGet reads its value. The SplFixedArray::count method counts every slot including nulls, SplFixedArray::toArray returns their values as an ordinary PHP array, and SplFixedArray::setSize changes the capacity.
$a=new SplFixedArray(3); $a->offsetSet(1,"B"); $a->offsetSet(2,"C"); $initial=$a->toArray();
$a->setSize(2); echo json_encode([$initial,$a->count(),$a->toArray()]);
echo PHP_EOL,json_encode([$a->offsetGet(0),$a->offsetGet(1)]);
try{$x=$a->offsetGet(2);}catch(OutOfBoundsException $e){echo PHP_EOL,get_class($e);}
[[null,"B","C"],2,[null,"B"]]
[null,"B"]
OutOfBoundsException
Examples
<?php
$a=new SplFixedArray(3); $a->offsetSet(1,"B"); $a->offsetSet(2,"C"); $initial=$a->toArray();
$a->setSize(2); echo json_encode([$initial,$a->count(),$a->toArray()]);
echo PHP_EOL,json_encode([$a->offsetGet(0),$a->offsetGet(1)]);
try{$x=$a->offsetGet(2);}catch(OutOfBoundsException $e){echo PHP_EOL,get_class($e);}
Result
[[null,"B","C"],2,[null,"B"]] [null,"B"] OutOfBoundsException