iterator_to_array
Description
The iterator_to_array of SPL for PHP copies the iterator into an array.
Syntax
iterator_to_array( Traversable|array $iterator, bool $preserve_keys = true ): array
Parameters
iterator
The iterator being copied.
preserve_keys
Whether to use the iterator element keys as index.
If a key is an array or object, a warning will be generated. null keys will be converted to an empty string, float keys will be truncated to their int counterpart, resource keys will generate a warning and be converted to their resource ID, and bool keys will be converted to integers.
NOTE: If this parameter is not set or set to true, duplicate keys will be overwritten. The last value with a given key will be in the returned array. Set this parameter to false to get all the values in any case.
Return
Returns an array containing the elements of the iterator.
Examples
1 · iterator
<? $array = [ "a" => "one", "b" => "two", "c" => "three" ]; $iterator = new ArrayIterator($array); $return = iterator_to_array($iterator); print_r($return); ?>
Array ( [a] => one [b] => two [c] => three )
2 · preserve_keys · false
<? $array = [ "a" => "one", "b" => "two", "c" => "three" ]; $iterator = new ArrayIterator($array); $preserve_keys = false; $return = iterator_to_array($iterator, $preserve_keys); print_r($return); ?>
Array ( [0] => one [1] => two [2] => three )
3 · preserve_keys · true
<? $array = [ "a" => "one", "b" => "two", "c" => "three", ]; $iterator = new ArrayIterator($array); $preserve_keys = true; $return = iterator_to_array($iterator, $preserve_keys); print_r($return); ?>
Array ( [a] => one [b] => two [c] => three )
4 · convert
<? $array = [ "from null value to empty string value" => null, 3.45 => "from float key to integer key", "from bool value to integer value" => true ]; $iterator = new ArrayIterator($array); $return = iterator_to_array($iterator); print_r($return); ?>
Array ( [from null value to empty string value] => [3] => from float key to integer key [from bool value to integer value] => 1 )