ArrayIterator

ArrayIterator implements SeekableIterator, ArrayAccess, Serializable, Countable

An iterator VIEW over an array: the Iterator protocol (rewind/valid/current/key/next) plus seek and array access, mutable while iterating; a different job from ArrayObject's container wrapping.

C C23

C23
#include <stdio.h>

/* C in reverse: iteration is a cursor struct plus a next() function */
typedef struct {
    const char *keys[8];
    int values[8];
    int len;
    int pos;
} Iter;

static int iter_next(Iter *it, const char **key, int *value) {
    if (it->pos >= it->len) {
        return 0;
    }
    *key = it->keys[it->pos];
    *value = it->values[it->pos];
    it->pos++;
    return 1;
}

int main(void) {
    Iter it = {{"a", "b", "c"}, {1, 2, 3}, 3, 0};
    const char *k;
    int v;
    iter_next(&it, &k, &v);
    const char *k1 = k;
    int v1 = v;
    iter_next(&it, &k, &v);
    printf("%s=%d %s=%d\n", k1, v1, k, v);
    printf("all:");
    Iter it2 = {{"a", "b", "c"}, {1, 2, 3}, 3, 0};
    while (iter_next(&it2, &k, &v)) {
        printf(" %s=%d", k, v);
    }
    printf("\ncount: %d a: %d\n", it2.len, it2.values[0]);
    return 0;
}
Output
a=1 b=2
all: a=1 b=2 c=3
count: 3 a: 1

C++ C++26

C++26
#include <iostream>
#include <map>
#include <string>

int main() {
    // C++ in reverse: begin()/end() iterators are generalized pointers;
    // ++it and *it drive the loop, range-for wraps them
    std::map<std::string, int> data{{"a", 1}, {"b", 2}, {"c", 3}};
    auto it = data.begin();
    auto first = *it;
    ++it;
    auto second = *it;
    std::cout << first.first << "=" << first.second << " "
              << second.first << "=" << second.second << "\n";
    std::cout << "all:";
    for (const auto &entry : data) {
        std::cout << " " << entry.first << "=" << entry.second;
    }
    std::cout << "\ncount: " << data.size() << " a: " << data.at("a") << "\n";
    return 0;
}
Output
a=1 b=2
all: a=1 b=2 c=3
count: 3 a: 1

C# v11.0.100

v11.0.100
using System.Collections.Generic;
using System.Linq;

// C# in reverse: IEnumerable/IEnumerator (MoveNext/Current) is the contract;
// Dictionary has no order - sort keys to iterate deterministically
var data = new Dictionary<string, int> { ["a"] = 1, ["b"] = 2, ["c"] = 3 };
var keys = new List<string>(data.Keys);
keys.Sort();
using var it = keys.GetEnumerator();
it.MoveNext();
var k1 = it.Current;
it.MoveNext();
var k2 = it.Current;
Console.WriteLine($"{k1}={data[k1]} {k2}={data[k2]}");
Console.WriteLine(string.Join(" ", keys.Select(k => $"{k}={data[k]}")));
Console.WriteLine($"count: {data.Count} a: {data["a"]}");
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

Go v1.27.4

v1.27.4
package main

import (
	"fmt"
	"sort"
)

// Go in reverse: no iterator objects for maps (range order is randomized);
// a next()-style closure over sorted keys mimics the iterator interface shape
func makeIter(m map[string]int) func() (string, int, bool) {
	keys := make([]string, 0, len(m))
	for k := range m {
		keys = append(keys, k)
	}
	sort.Strings(keys)
	i := 0
	return func() (string, int, bool) {
		if i >= len(keys) {
			return "", 0, false
		}
		k := keys[i]
		i++
		return k, m[k], true
	}
}

func main() {
	data := map[string]int{"a": 1, "b": 2, "c": 3}
	next := makeIter(data)
	k1, v1, _ := next()
	k2, v2, _ := next()
	fmt.Printf("%s=%d %s=%d\n", k1, v1, k2, v2)
	fromStart := makeIter(data) // a fresh pass: the first closure is drained
	parts := []string{}
	for {
		k, v, ok := fromStart()
		if !ok {
			break
		}
		parts = append(parts, fmt.Sprintf("%s=%d", k, v))
	}
	fmt.Println(parts)
	fmt.Println("count:", len(data), "a:", data["a"])
}
Output
a=1 b=2
[a=1 b=2 c=3]
count: 3 a: 1

Java v27.0.1

v27.0.1
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        // Java in reverse: collections ship java.util.Iterator (hasNext/next);
        // LinkedHashMap keeps insertion order like a PHP array
        Map<String, Integer> data = new LinkedHashMap<>();
        data.put("a", 1);
        data.put("b", 2);
        data.put("c", 3);
        Iterator<Map.Entry<String, Integer>> it = data.entrySet().iterator();
        Map.Entry<String, Integer> first = it.next();
        Map.Entry<String, Integer> second = it.next();
        System.out.println(first.getKey() + "=" + first.getValue() + " "
                + second.getKey() + "=" + second.getValue());
        StringBuilder all = new StringBuilder();
        for (Map.Entry<String, Integer> e : data.entrySet()) {
            if (all.length() > 0) all.append(" ");
            all.append(e.getKey()).append("=").append(e.getValue());
        }
        System.out.println(all);
        System.out.println("count: " + data.size() + " a: " + data.get("a"));
    }
}
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

JavaScript v26.13.1

v26.13.1
// JS in reverse: iteration is the Symbol.iterator protocol - hand-roll next()
// or use a generator, which ships the protocol for you
const data = { a: 1, b: 2, c: 3 };
function makeIterator(obj) {
  const entries = Object.entries(obj);
  let i = 0;
  return {
    next: () =>
      i < entries.length
        ? { value: entries[i++], done: false }
        : { value: undefined, done: true },
  };
}
const it = makeIterator(data);
const first = it.next().value;
const second = it.next().value;
console.log(`${first[0]}=${first[1]} ${second[0]}=${second[1]}`);
function* iterate(obj) {
  for (const [k, v] of Object.entries(obj)) yield `${k}=${v}`;
}
console.log([...iterate(data)].join(" "));
console.log("count:", Object.keys(data).length, "a:", data.a);
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

PHP v8.6.0

v8.6.0
// ArrayIterator: an iterator VIEW over an array - rewind/valid/current/key/next
// by hand, plus SeekableIterator seek, ArrayAccess and Countable. The ten
// sort/flags/serialize methods are deprecated since 8.6 (see notes)
$it = new ArrayIterator(["a" => 1, "b" => 2, "c" => 3]);
$it->rewind();
echo $it->valid() ? "valid\n" : "done\n";
echo $it->key(), "=", $it->current(), "\n";
$it->next();
echo $it->key(), "=", $it->current(), "\n";
$it->seek(0); // seek by ordinal position, not by key
echo "seek0=", $it->current(), "\n";
$keys = [];
foreach ($it as $k => $v) { $keys[] = $k; } // foreach works via Iterator
echo "keys: ", implode(",", $keys), "\n";
$it->offsetSet("d", 4);
echo count($it), " ", json_encode($it->getArrayCopy()), " ", $it->offsetGet("d"), "\n";
Output
valid
a=1
b=2
seek0=1
keys: a,b,c
4 {"a":1,"b":2,"c":3,"d":4} 4

Python v3.15.2

v3.15.2
# Python in reverse: iteration is a protocol - __iter__/__next__; the for loop
# drives it, and the builtins iter()/next() make it first-class
data = {"a": 1, "b": 2, "c": 3}
it = iter(data.items())
first = next(it)
second = next(it)
print(f"{first[0]}={first[1]} {second[0]}={second[1]}")
print(" ".join(f"{k}={v}" for k, v in data.items()))
print("count:", len(data), "a:", data["a"])
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

Rust v1.99.1

v1.99.1
// Rust in reverse: the Iterator trait (next -> Option) powers every loop;
// Vec<T> ships it, and collect/map compose on top
fn main() {
    let data = vec![("a", 1), ("b", 2), ("c", 3)];
    let mut it = data.iter();
    let first = it.next().unwrap();
    let second = it.next().unwrap();
    println!("{}={} {}={}", first.0, first.1, second.0, second.1);
    let all: Vec<String> = data.iter().map(|(k, v)| format!("{}={}", k, v)).collect();
    println!("{}", all.join(" "));
    println!("count: {} a: {}", data.len(), data[0].1);
}
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

TypeScript v26.13.1

v26.13.1
// TS in reverse: the protocol gets precise types - Iterator/IteratorResult
// over entry tuples; a generator keeps the shape without ceremony
const data: Record<string, number> = { a: 1, b: 2, c: 3 };
const entries = Object.entries(data);
let cursor = 0;
const it: Iterator<[string, number]> = {
  next(): IteratorResult<[string, number]> {
    return cursor < entries.length
      ? { value: entries[cursor++], done: false }
      : { value: undefined, done: true };
  },
};
const first = it.next().value as [string, number];
const second = it.next().value as [string, number];
console.log(`${first[0]}=${first[1]} ${second[0]}=${second[1]}`);
function* iterate(obj: Record<string, number>): Generator<string> {
  for (const [k, v] of Object.entries(obj)) yield `${k}=${v}`;
}
console.log([...iterate(data)].join(" "));
console.log("count:", Object.keys(data).length, "a:", data.a);
Output
a=1 b=2
a=1 b=2 c=3
count: 3 a: 1

Language differences

C: iteration is a hand-written cursor struct plus a next() function (shown); no language-level iterator interface - libraries (glib's GHashTableIter and friends) each make their own.

C++: begin()/end() iterators are generalized pointers - ++it/*it drive the loop, range-for is sugar; the iterator categories (input/forward/bidirectional/random access) rank by capability.

C#: IEnumerable/IEnumerator (MoveNext/Current) is the iteration contract; yield return compiles into a state machine - the ready-made equivalent of ArrayIterator.

Go: no iterator objects - range is the built-in iteration; the iter.Seq functional iterator (since 1.23) is the newer idiom (the example mimics the same shape with a next closure).

Java: java.util.Iterator (hasNext/next) is the standard collection iteration interface, Iterable is the foreach-able marker; ListIterator adds bidirectional movement, matching PHP's seek ability.

JavaScript: the iteration protocol is Symbol.iterator + next() returning {value, done}; generators are the cheapest implementation (the example shows both).

PHP: ArrayIterator is an iterator VIEW over an array (SeekableIterator + ArrayAccess + Serializable + Countable) - division of labor with ArrayObject (A12, container wrapping): ArrayObject owns the data and the OO interface, getIterator() hands out an ArrayIterator dedicated to traversal (values/keys mutable mid-iteration). Deprecation teaching point (8.6): getFlags/setFlags/asort/ksort/uasort/uksort/natsort/natcasesort/serialize/unserialize are deprecated - move sorting/serialization to the plain array outside, flags go through the constructor (the example sticks to the non-deprecated surface). Note: passing an array to the constructor COPIES it; mutating the iterator never writes back.

Python: the protocol is __iter__/__next__ (StopIteration on exhaustion); the for loop is sugar over it, and the builtins iter()/next() make it first-class (the example drives dict.items() by hand).

Rust: the Iterator trait (next() -> Option<Item>) is the core abstraction; for desugars onto it, and the collect/map/filter combinator ecosystem is the declarative version of manual rewind/valid/next.

TypeScript: the same JS Iterator/Iterable structural typing; TS's value is pinning the element type in the Iterator<T> declaration (shown).