CKTIS / PHP
Resize a SplFixedArray with SplFixedArray::setSize
Resize an existing `SplFixedArray`. Growing it adds slots initialized to `null`; shrinking it discards values from the end.
Version: PHP 8.3
Syntax
PHP 8.3: $array->setSize(int $size) → bool (tentative return type; returns true on normal completion). $array is a SplFixedArray instance.SplFixedArray::setSize changes the size of an existing SPL object rather than creating a new one. It is an instance method: call it as $array->setSize($size). The int argument $size is the target number of slots, not the amount to add or the last index. For a positive size, the indexes run from 0 to $size - 1.
Growing keeps the existing values and fills the new slots with null. Shrinking keeps values at indexes below $size and discards the rest. Growing again does not recover those values. A size of 0 removes every slot. Setting the same size leaves the contents unchanged.
In PHP 8.3 the method's tentative return type is bool, but it returns true on normal completion, not the new size. To read the size, use $array->getSize(). PHP 8.4 changed the tentative return type to true. A negative size throws ValueError. PHP_INT_MAX is the upper bound for an int, not a guarantee that there is enough memory for that many slots.
Examples
<?php
declare(strict_types=1);
$array = new SplFixedArray(2);
$array[0] = 10;
$array[1] = 20;
$result = $array->setSize(3);
echo json_encode([$result, $array->getSize(), $array[0], $array[2]]), "\n";
$array->setSize(1);
echo $array->getSize(), "\n";
$array->setSize(2);
echo json_encode([$array->getSize(), $array[0], $array[1]]), "\n";
try {
$array->setSize(-1);
} catch (ValueError $error) {
echo "ValueError\n";
}
Result
[true,3,10,null] 1 [2,10,null] ValueError
The first line shows the return value `true`, the size `3`, the preserved value `10`, and a new `null` slot. After shrinking to `1` and growing back to `2`, index `1` contains `null`, not the old `20`. The last line comes from catching `ValueError`.
Related lessons
- PHP · Lesson 66 · Advanced · Version: 2