Base de conocimientosCentro de exámenes
ESEspañol
Elegir idioma13

CKTIS / PHP

SplFixedArray

Reserva posiciones indexadas desde cero.

Versión: PHP 8.4; repository runtime, production runtime not attested

Sintaxis

new SplFixedArray($size)

Reserva posiciones indexadas desde cero. Las posiciones sin asignar contienen null y count mide la capacidad actual. setSize la cambia y al reducirla descarta las últimas posiciones. Un índice fuera de límites en PHP 8.4 lanza OutOfBoundsException. El método SplFixedArray::offsetSet escribe en una posición asignada y SplFixedArray::offsetGet lee su valor. El método SplFixedArray::count cuenta todas las posiciones, incluidas las de valor null, SplFixedArray::toArray devuelve sus valores en un array ordinario y SplFixedArray::setSize cambia el tamaño.

$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

Ejemplos

<?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);}

Resultado

[[null,"B","C"],2,[null,"B"]]
[null,"B"]
OutOfBoundsException

Fuentes