The SplFixedArray class

(PHP 5 >= 5.3.0, PHP 7, PHP 8)

Introduction

The SplFixedArray class provides the main functionalities of array. The main difference between a SplFixedArray and a normal PHP array is that the SplFixedArray must be resized manually and allows only integers within the range as indexes. The advantage is that it uses less memory than a standard array.

Class synopsis

classSplFixedArrayimplementsIteratorAggregate, ArrayAccess, Countable, JsonSerializable {
public__construct(int$size = 0)
publiccount(): int
publiccurrent(): mixed
publicstaticfromArray(array$array, bool$preserveKeys = true): SplFixedArray
publicgetSize(): int
publickey(): int
publicnext(): void
publicoffsetExists(int$index): bool
publicoffsetGet(int$index): mixed
publicoffsetSet(int$index, mixed$value): void
publicoffsetUnset(int$index): void
publicrewind(): void
publicsetSize(int$size): bool
publictoArray(): array
public__unserialize(array$data): void
publicvalid(): bool
public__wakeup(): void
}

Changelog

VersionDescription
8.2.0 The SplFixedArray::__serialize() and SplFixedArray::__unserialize() magic methods have been added to SplFixedArray.
8.1.0SplFixedArray implements JsonSerializable now.
8.0.0SplFixedArray implements IteratorAggregate now. Previously, Iterator was implemented instead.

Examples

Example #1 SplFixedArray usage example

<?php
// Initialize the array with a fixed length
$array = new SplFixedArray(5);

$array[1] = 2;
$array[4] = "foo";

var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)

var_dump($array["4"]); // string(3) "foo"

// Increase the size of the array to 10
$array->setSize(10);

$array[9] = "asdf";

// Shrink the array to a size of 2
$array->setSize(2);

// The following lines throw a RuntimeException: Index invalid or out of range
try {
var_dump($array["non-numeric"]);
} catch(
RuntimeException $re) {
echo
"RuntimeException: ".$re->getMessage()."\n";
}

try {
var_dump($array[-1]);
} catch(
RuntimeException $re) {
echo
"RuntimeException: ".$re->getMessage()."\n";
}

try {
var_dump($array[5]);
} catch(
RuntimeException $re) {
echo
"RuntimeException: ".$re->getMessage()."\n";
}
?>

The above example will output:

 NULL int(2) string(3) "foo" RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range 

Table of Contents

To Top