CKTIS / PHP
SplFixedArray::count — get the current size
`SplFixedArray::count()` returns the current number of slots, including slots that contain `null`, rather than the number of non-null values.
Version: PHP 8.3; extension availability may vary
Syntax
public function count(): intSplFixedArray::count is an instance method that takes no parameters. Calling $array->count() returns the current size as an int without changing the array. The constructor initializes every slot to null, but every slot still counts. Assigning a value to an existing slot does not change the result.
$array->getSize() returns the same size. Although SplFixedArray implements Countable, for an instance of SplFixedArray itself (not a subclass), the global function \count($array) gets the size directly through the object's native count handler without calling the public count() method. The :: notation identifies the method in documentation; use -> to call it on an object.
Change the size explicitly with $array->setSize($size). Growing the array adds slots initialized to null; shrinking it discards slots and their values beyond the new range. To count non-null values instead, iterate over the array and count only those for which $value !== null.
Examples
<?php
$array = new \SplFixedArray(3);
echo $array->count(), "\n";
$array[1] = 'PHP';
echo $array->count(), ' ', \count($array), ' ', $array->getSize(), "\n";
$array->setSize(5);
echo $array->count(), "\n";
Result
3 3 3 3 5
All three slots start out as `null`. After storing `'PHP'` at index `1`, all three ways of reading the size still return `3`. Only `setSize(5)` changes the size to `5`.
Related lessons
- PHP · Lesson 66 · Advanced · Version: 2