When talking about array data structure in general (not in PHP), we know that arrays

  • can hold any data type as value
  • are fixed in size (have fixed capacity)
  • have random access (can get or set items using indexes in constant time O(1))

In PHP, arrays are mighty dynamic by default, but in our previous article we have seen how we can simulate fixed array data structure in PHP.

Since arrays are fixed in size by default, how can we make them dynamic? For example, how can we accomplish adding an item to an array instance which is already full? This is typically done like this:

  1. create a new array which is double in size when comparing to our old array
  2. copy all values from the old array to the new array
  3. take the existing reference which points to the old array and make it point to the new array
  4. insert value to the array

Update (31 October 2026): The DynamicArray file in the repository is a placeholder, and the repository does not include DynamicArrayTest.php. The explanation and screenshots below describe the original experiment, which cannot currently be reproduced from that file. The FixedArray article includes the implemented base class and its tests.

For the original experiment, I used a DynamicArray based on FixedArray. I cloned the repository into an alg-ds-php folder, installed its dependencies with composer install, and used the PsySH REPL to explore the array’s behaviour.

I will create a new DynamicArray instance with initial capacity set to 2. I’ll try to add three items to that array, and then check the available capacity.

Original PsySH session showing array capacity increasing from 2 to 4 after adding a third item

By using this concept we get a higher level data structure which uses basic array data structure behind the scenes. In that way we still get constant time when accessing values using index, but have a dynamic behavior when it comes to the array size.

All of this comes out-of-the-box when we use default array data structure in PHP, but as developers we have to be aware of array basic data structure concepts in general, and how we can build higher level abstractions on those basic data structure concepts.

The original test screenshot is retained below for context. The corresponding test file is not available in the linked repository.

Original PHPUnit output reporting 3 passing DynamicArray tests and 3 assertions

Note that the original SplFixedArray class (which is used in my code behind the scenes) has a setSize() method which allows to change the size of an array. I have purposely omitted such option to show how to create a dynamic array manually.