Thursday, October 23, 2025
HomeLanguagesPHP iterator_to_array() Function

PHP iterator_to_array() Function

The iterator_to_array() function is an inbuilt function in PHP that is used to copy the iterator object (e.g. objects implementing the Iterator or IteratorAggregate interface) into an array. An iterator is an object that allows you to loop through a set of values one at a time without knowing the underlying data structure.

Syntax:

array iterator_to_array(
Traversable | array $iterator, 
bool $preserve_keys = true
)

Parameters: This function accepts two parameters that are described below.

  • $iterator: This is the iterator that you want to copy into an array.
  • $preserve_keys: This is an optional parameter. It specifies whether to use iterators keys as arrays keys. By default this value is true. meaning the array will preserve the original keys from the iterator. If set to false, the array will be reindexed with numeric keys starting from 0.

Return Values: The iterator_to_array() function returns the array with all containing values of iterator.

Program 1: The following program demonstrates the iterator_to_array() function.

PHP




<?php
  
class SimpleIterator implements Iterator {
    private $position = 0;
      
    private $data = array('apple', 
        'banana', 'cherry', 'date');
  
    public function rewind() {
        $this->position = 0;
    }
  
    public function current() {
        return $this->data[$this->position];
    }
  
    public function key() {
        return $this->position;
    }
  
    public function next() {
        ++$this->position;
    }
  
    public function valid() {
        return isset($this->data[$this->position]);
    }
}
  
$iterator = new SimpleIterator();
$array = iterator_to_array($iterator);
  
print_r($array);
  
?>


Output

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

Program 2: The following program demonstrates the iterator_to_array() function.

PHP




<?php
      
// Create an Array
$data = [100, 200, 300, 400];
  
// Create an ArrayIterator with array data
$iterator = new ArrayIterator($data);
  
// Convert the iterator to an array
// without preserving keys
$array = iterator_to_array($iterator, false);
  
// Print the resulting array
print_r($array);
  
?>


Output

Array
(
[0] => 100
[1] => 200
[2] => 300
[3] => 400
)

Reference: https://www.php.net/manual/en/function.iterator-to-array.php

RELATED ARTICLES

Most Popular

Dominic
32361 POSTS0 COMMENTS
Milvus
88 POSTS0 COMMENTS
Nango Kala
6728 POSTS0 COMMENTS
Nicole Veronica
11892 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11954 POSTS0 COMMENTS
Shaida Kate Naidoo
6852 POSTS0 COMMENTS
Ted Musemwa
7113 POSTS0 COMMENTS
Thapelo Manthata
6805 POSTS0 COMMENTS
Umr Jansen
6801 POSTS0 COMMENTS