Creating fixed size arrays with the SplFixedArray method

So far, we have explored PHP arrays and we know, we do not define the size of the arrays. PHP arrays can grow or shrink as per our demand. This flexibility comes with a great inconvenience regarding memory usage. We are going to explore that in this section. For now, let us focus on creating fixed size arrays using the SPL library.

Why do we need a fixed size array? Does it have any added advantage? The answer is that when we know we only need a certain number of elements in an array, we can use a fixed array to reduce the memory usage. Before going to the memory use analysis, let us have some examples of using the SplFixedArray method:

$array = new SplFixedArray(10);

for ($i = 0; $i < 10; $i++)
$array[$i] = $i;

for ($i = 0; $i < 10; $i++)
echo $array[$i] . " ";

First, we are creating a new SplFixedArray object with a defined size of 10. The remaining lines actually follow the same principle which we use in regular PHP array value assignment and retrieval. If we want to access an index which is out of the range (here it is 10), it will throw an exception:

PHP Fatal error:  Uncaught RuntimeException: Index invalid or out of range

The basic difference between a PHP array and SplFixedArray are:

  • SplFixedArray must have a fixed defined size
  • The indexes of SplFixedArray must be integers and within the range of 0 to n, where n is the size of the array we defined

The SplFixedArray method can be very handy when we have a lot of defined arrays with known size or have an upper limit for the maximum required size of the array. But if we do not know the array size, then it is better to use a PHP array.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset