Changing from a PHP array to SplFixedArray

We have seen how we can create a SplFixedArray with a fixed length. What if I want to create an array to SplFixedArray during runtime? The following code block shows how to achieve it:

$array =[1 => 10, 2 => 100, 3 => 1000, 4 => 10000]; 
$splArray = SplFixedArray::fromArray($array);
print_r($splArray);

Here we are constructing a SplFixedArray from an existing array $array using the static method fromArray of the SplFixedArray class. Then we are printing the array using the PHP print_r function. It will show an output like this:

SplFixedArray Object 
(
[0] =>
[1] => 10
[2] => 100
[3] => 1000
[4] => 10000
)

We can see the array has been now converted to an SplFixedArray and it maintained the index number exactly as it was in the actual array. Since the actual array did not have 0 index defined, here index 0 is kept as null. But if we want to ignore the indexes from the previous array and assign them new indexes, then we have to change the second line of the previous code to this:

$splArray = SplFixedArray::fromArray($array,false); 

Now if we print the array again, we will have the following output:

SplFixedArray Object
(
[0] => 10
[1] => 100
[2] => 1000
[3] => 10000
)
If we want to convert an array to a fixed array during runtime, it is a better idea to unset the regular PHP array if it is not being used later on. It will save memory usage if it is a big array.

 

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

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