SPL data structures
Difference from PHP Array
PHP's default Array type is actually implemented as ordered hash maps, which allow us to create arrays that consist of key/value pairs where values can be of any type and keys can be either numbers or strings. This is not traditionally how arrays are created, however.
So as you can see from this illustration a normal PHP array can be viewed more like an an ordered set of key/value pairs, where each key can map to any value. Notice in this array we have keys that are both numbers and strings, as well as values of different types and the key has no bearing on the order of the elements.
So the above code would give us exactly what we'd expect.
Regular PHP arrays are also dynamically sized for us. They grow and shrink as we push and pop values to and from the array, automatically.
However, in a traditional array the size is fixed and consists entirely of the same type of value. Also, rather than keys each value is access by its index, which can be deduced by its offset in the array.
Since we would know the size of a given type and the fixed size of the array an offset is then the
type size * n were
n represents the value's position in the array. So in the example above
$arr gives us
1, the first element in the array and
$arr gives us
2, and so on.
SplFixedArray, however, doesn't restrict the type of values. It only restricts the keys to number types. It's also of a fixed size.
This makes SplFixedArrays more efficient than normal PHP arrays in one particular way. They are more compact so they require less memory.
Instantiating the array
SplFixedArray is implemented as an object, but it can be accessed with the same familiar syntax that you access a normal PHP array since they implement the
ArrayAccess interface. They also implement
Iterator interfaces so they behave the same way you'd be used to arrays behaving in PHP (i.e. things like
foreach($arr as $k => $v) work the same way for SplFixedArray as they do normal arrays in PHP.
The SplFixedArray constructor takes one argument, which is the size of the array.
This gives you what you would expect.
This also works as expected.
Notice in SplFixedArray, unlike a normal PHP Array, the key does depict the order of the element in our array, because it is a true index and not just a map.
Resizing the array
Just keep in mind that because the array is of a fixed size, count will always return the same value. So while
unset($arr) will result in
$arr === null,
count($arr) still remains
So to resize the array you will need to call on the
Now we get...
Import to SplFixedArray & Export from SplFixedArray
You can also import/export a normal PHP Array into and out of an SplFixedArray with the
Going the other way.