iterator_to_array

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

Materializes a lazy iterator/generator into an array; with preserve_keys=true later duplicates overwrite (manual-stated), false keeps all values with rebuilt keys.

C C23

C23
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* C has no iterator protocol: materializing a lazy sequence means a manual
   loop appending into a grown buffer */
int main(void) {
    const char *keys[] = {"a", "b", "a"};
    const int vals[] = {1, 2, 3};
    size_t n = 3;
    char **rows = malloc(n * sizeof *rows);
    for (size_t i = 0; i < n; i++) {
        rows[i] = malloc(strlen(keys[i]) + 8);
        sprintf(rows[i], "%s=%d", keys[i], vals[i]);
    }
    for (size_t i = 0; i < n; i++) {
        printf("%s%s", rows[i], i + 1 < n ? " " : "\n");
        free(rows[i]);
    }
    free(rows);
    return 0;
}
Output
a=1 b=2 a=3

C++ C++26

C++26
#include <iostream>
#include <ranges>
#include <string>
#include <vector>

int main() {
    // C++20 ranges are lazy; materialize with a manual loop (ranges::to is
    // C++23 and not yet everywhere)
    auto nums = std::views::iota(1, 4)
              | std::views::transform([](int n) { return "abcd"[n - 1] + std::string("=") + std::to_string(n); });
    std::vector<std::string> list;
    for (const auto &s : nums) list.push_back(s);
    for (size_t i = 0; i < list.size(); i++) {
        std::cout << list[i] << (i + 1 < list.size() ? " " : "\n");
    }
    return 0;
}
Output
a=1 b=2 c=3

C# v11.0.100

v11.0.100
// LINQ is lazy end to end: nothing runs until ToList() materializes
int materialized = 0;
IEnumerable<(string Key, int Val)> Lazy()
{
    materialized++;
    yield return ("a", 1);
    yield return ("b", 2);
    yield return ("a", 3);
}
var query = Lazy().Where(p => p.Val > 0);
Console.WriteLine("before ToList: " + (materialized == 0));
var list = query.ToList();
Console.WriteLine("after ToList: " + (materialized == 1));
Console.WriteLine(list.Count);
// ToDictionary via GroupBy keeps the last value per key (preserve_keys=true)
var dict = list.GroupBy(p => p.Key).ToDictionary(g => g.Key, g => g.Last().Val);
Console.WriteLine($"{dict["a"]} {dict["b"]}");
Output
before ToList: True
after ToList: True
3
3 2

Go v1.27.4

v1.27.4
package main

import "fmt"

// Go 1.23+ push iterators: a func that yields (k, v) to a callback;
// the protocol never materializes - collect by hand with append
func pairs(yield func(string, int) bool) {
	if !yield("a", 1) {
		return
	}
	if !yield("b", 2) {
		return
	}
	yield("a", 3)
}

func main() {
	var list []string
	for k, v := range pairs {
		list = append(list, fmt.Sprintf("%s=%d", k, v))
	}
	fmt.Println(list)
	m := map[string]int{}
	for k, v := range pairs {
		m[k] = v
	}
	fmt.Println(m["a"], m["b"])
}
Output
[a=1 b=2 a=3]
3 2

Java v27.0.1

v27.0.1
import java.util.AbstractMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args) {
        // Stream.toList() (Java 16+) materializes a lazy stream eagerly
        List<Map.Entry<String, Integer>> list = Stream
                .<Map.Entry<String, Integer>>of(
                        new AbstractMap.SimpleEntry<>("a", 1),
                        new AbstractMap.SimpleEntry<>("b", 2),
                        new AbstractMap.SimpleEntry<>("a", 3))
                .toList();
        System.out.println(list);
        // toMap with merge keeps the last value per key (like preserve_keys=true)
        Map<String, Integer> m = Stream
                .<Map.Entry<String, Integer>>of(
                        new AbstractMap.SimpleEntry<>("a", 1),
                        new AbstractMap.SimpleEntry<>("b", 2),
                        new AbstractMap.SimpleEntry<>("a", 3))
                .collect(Collectors.toMap(
                        Map.Entry::getKey, Map.Entry::getValue, (x, y) -> y, LinkedHashMap::new));
        System.out.println(m);
    }
}
Output
[a=1, b=2, a=3]
{a=3, b=2}

JavaScript v26.13.1

v26.13.1
// Any Symbol.iterator object materializes via Array.from or spread
function* pairs() {
    yield ["a", 1];
    yield ["b", 2];
    yield ["a", 3];
}
const arr = Array.from(pairs());
console.log(arr.length, arr[0]);
console.log([...pairs()].length);
// Object.fromEntries keeps the last value per key (like preserve_keys=true)
console.log(Object.fromEntries(arr));
Output
3 [ 'a', 1 ]
3
{ a: 3, b: 2 }

PHP v8.6.0

v8.6.0
// Materialize a lazy generator into an array; preserve_keys=true keeps
// element keys - duplicate keys keep the LAST value (manual)
$gen = (function () { yield 'a' => 1; yield 'b' => 2; yield 'a' => 3; })();
var_dump(iterator_to_array($gen));
// preserve_keys=false: every value lands in the result, keys rebuilt
$gen2 = (function () { yield 'a' => 1; yield 'b' => 2; yield 'a' => 3; })();
var_dump(iterator_to_array($gen2, false));
echo json_encode(iterator_to_array(new ArrayIterator([10, 20]))), "\n";
Output
array(2) {
  ["a"]=>
  int(3)
  ["b"]=>
  int(2)
}
array(3) {
  [0]=>
  int(1)
  [1]=>
  int(2)
  [2]=>
  int(3)
}
[10,20]

Python v3.15.2

v3.15.2
def gen():
    yield ("a", 1)
    yield ("b", 2)
    yield ("a", 3)

# list(generator) materializes a lazy iterator eagerly
pairs = list(gen())
print(pairs)
# dict() keeps the last value per key (like preserve_keys=true)
print(dict(pairs))
Output
[('a', 1), ('b', 2), ('a', 3)]
{'a': 3, 'b': 2}

Rust v1.99.1

v1.99.1
fn pairs() -> std::vec::IntoIter<(&'static str, i32)> {
    vec![("a", 1), ("b", 2), ("a", 3)].into_iter()
}

fn main() {
    // collect::<Vec<_>>() materializes a lazy Iterator eagerly; the Iterator
    // trait is a zero-cost abstraction over pull-based iteration
    let list: Vec<_> = pairs().collect();
    println!("{:?}", list);
    // HashMap collect keeps the last value per key (like preserve_keys=true)
    let m: std::collections::HashMap<&str, i32> = pairs().collect();
    println!("{} {}", m["a"], m["b"]);
}
Output
[("a", 1), ("b", 2), ("a", 3)]
3 2

TypeScript v26.13.1

v26.13.1
// Any Symbol.iterator object materializes via Array.from or spread
function* pairs(): Generator<[string, number]> {
    yield ["a", 1];
    yield ["b", 2];
    yield ["a", 3];
}
const arr = Array.from(pairs());
console.log(arr.length, arr[0]);
console.log([...pairs()].length);
console.log(Object.fromEntries(arr));
Output
3 [ 'a', 1 ]
3
{ a: 3, b: 2 }

Language differences

C: no iterator protocol - "materializing a lazy sequence" is a hand loop filling a malloc'd buffer; a lazy generator means writing your own state machine (or setjmp tricks).

C++: C++20 views pipelines are fully lazy - materialize with a hand loop (ranges::to<vector> is C++23, toolchain support still sparse); views::iota | views::transform mirrors a generator chain.

C#: LINQ's end-to-end laziness is the design core - Lazy().Where(...) builds a query that runs zero steps until ToList() (verified with a counter before/after in this example); duplicate-key policy needs GroupBy + Last() (ToDictionary throws on duplicates outright); C#'s yield return iterators pioneered the feature many languages borrowed.

Go: the 1.23+ range-over-func push iterators have no materialization in the protocol - "collect" is a loop with append; collecting into a map keeps the last value per key; Go idiom leans pull-style range rather than lazy streams.

Java: Stream.toList() (16+)/collect(Collectors.toList()) materializes; toMap needs an explicit merge function ((x, y) -> y keeps the last value per key) - without it, duplicates throw IllegalStateException; Stream is lazy pull-style, terminal ops trigger all computation.

JavaScript: Array.from(iterator) / [...iterator] are two native materializations; Object.fromEntries keeps the last value per key (matching preserve_keys=true); a function* generator is consumed once, and iterating an exhausted one just ends (PHP generators throw on re-iteration - a difference worth noting).

PHP: iterator_to_array is SPL's lazy-to-array switch - preserve_keys=true (default) keeps element keys and the last duplicate wins (manual-stated), false keeps every value with rebuilt integer keys; the manual also lists key normalization (null keys to empty string, floats truncated, bools to int); passing false is the standard "I want every value" move; it accepts Traversable|array (arrays too since PHP 8.1).

Python: list(generator) is the most direct; dict(pairs) keeps the last value per key; tuple/set materialize likewise; iterating an exhausted generator silently ends (no exception).

Rust: collect::<Vec<_>>() is the most elegant materialization - the Iterator trait is a zero-cost abstraction over pull-based iteration: lazy composition (map/filter allocate nothing) monomorphized at compile time, one allocation on collect; collect::<HashMap<_,_>>() keeps the last value per key; an exhausted Iterator cannot be reused (the type system guarantees it).

TypeScript: same as JavaScript (Array.from/spread + Object.fromEntries); Generator<[string, number]> annotations make the materialized type exact.