(Available since version 1.0)
The DynamicArray class builds on the functionality of SplFixedArray, providing an array that can grow (and shrink) automatically as it is used.
The DynamicArray class provides the main functionalities of array. The main differences between a DynamicArray and a normal PHP array is that the DynamicArray allows only integers within the range as indexes. The advantage is that it allows a faster array implementation.
The array is grown simply by adding an element to the end of the array.
The API is the same as SplFixedArray but with the following extra methods:
$array
[,
bool
$save_indexes
= true
] )
Example #1 DynamicArray usage example
<?php
require 'vendor/autoload.php'; // A PSR-4 or PSR-0 autoloader
use SEIDS\Arrays\Dynamic\DynamicArray;
// Initialize the array with an initial length (optional)
$array = new DynamicArray(5);
$array[1] = 2;
$array[4] = "foo";
var_dump($array[0]); // NULL
var_dump($array[1]); // int(2)
var_dump($array["4"]); // string(3) "foo"
// Increase the size of the array to 10
$array->setSize(10);
$array[9] = "asdf";
// Shrink the array to a size of 2
$array->setSize(2);
// Add two elements to the end
$array->push("second to last");
$array[] = "last";
var_dump($array->toArray());
// The following lines throw a RuntimeException: Index invalid or out of range
try {
var_dump($array["non-numeric"]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}
try {
var_dump($array[-1]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}
try {
var_dump($array[5]);
} catch(RuntimeException $re) {
echo "RuntimeException: ".$re->getMessage()."\n";
}
?>
The above example will output:
NULL int(2) string(3) "foo" array(4) { [0] => NULL [1] => int(2) [2] => string(14) "second to last" [3] => string(4) "last" } RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range RuntimeException: Index invalid or out of range
The internal array.
The count or external size.