Current Location: Home> Function Categories> iterator_to_array

iterator_to_array

Copy elements from the iterator to an array
Name:iterator_to_array
Category:SPL
Programming Language:php
One-line Description:Convert an iterator to an array

Function name: iterator_to_array()

Function description: Convert an iterator to an array

Applicable version: PHP 5, PHP 7

Usage: iterator_to_array(Iterator $iterator, bool $use_keys = true)

parameter:

  • $iterator: Iterator object to convert to an array.
  • $use_keys (optional): Specifies whether to use the iterator's key as the key of the array. Default is true.

Return value: Returns the converted array.

Example:

  1. Convert the iterator to an array and keep the keys:
 $iterator = new ArrayIterator(['a' => 'apple', 'b' => 'banana', 'c' => 'cherry']); $array = iterator_to_array($iterator); print_r($array);

Output:

 Array ( [a] => apple [b] => banana [c] => cherry )
  1. Convert the iterator to an array, without retaining the keys:
 $iterator = new ArrayIterator(['apple', 'banana', 'cherry']); $array = iterator_to_array($iterator, false); print_r($array);

Output:

 Array ( [0] => apple [1] => banana [2] => cherry )

Notes:

  • If the keys in the iterator are not unique, the following values ​​override the previous values.
  • If a non-unique key is used and the key is not retained, the keys of the array will be incremented from 0.
Similar Functions
Popular Articles