HOME C C++ PYTHON JAVA HTML CSS JAVASCRIPT BOOTSTRAP JQUERY REACT PHP SQL AJAX JSON DATA SCIENCE AI

PHP Iterables

An iterable is any value which can be looped through with a foreach() loop.

In PHP, an iterable is a data type that can be iterated over using a foreach loop.

This includes arrays and objects that implement the Traversable interface.

Iterables allow you to loop over a collection of data elements without needing to know the specific internal structure of that collection.

Syntax

<?php

function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

$arr = ["a", "b", "c"];
printIterable($arr);

?>

Output

PHP - Creating Iterables

Arrays All arrays are iterables, so any array can be used as an argument of a function that requires an iterable.

Iterators Any object that implements the Iterator interface can be used as an argument of a function that requires an iterable.
An iterator contains a list of items and provides methods to loop through them. It keeps a pointer to one of the elements in the list. Each item in the list should have a key which can be used to find the item.
An iterator must have these methods:

current() - Returns the element that the pointer is currently pointing to. It can be any data type

key() Returns the key associated with the current element in the list. It can only be an integer, float, boolean or string

next() Moves the pointer to the next element in the list

rewind() Moves the pointer to the first element in the list

valid() If the internal pointer is not pointing to any element (for example, if next() was called at the end of the list), this should return false. It returns true in any other case


Example

// Example 1: Iterating over an array
$array = [1, 2, 3, 4, 5];
foreach ($array as $value) {
    echo $value . "\n";
}

// Example 2: Iterating over an object that implements Traversable
class MyIterator implements Iterator {
    private $position = 0;
    private $array = ['a', 'b', 'c', 'd', 'e'];
    
    public function rewind() {
        $this->position = 0;
    }
    
    public function current() {
        return $this->array[$this->position];
    }
    
    public function key() {
        return $this->position;
    }
    
    public function next() {
        ++$this->position;
    }
    
    public function valid() {
        return isset($this->array[$this->position]);
    }
}

$obj = new MyIterator();
foreach ($obj as $key => $value) {
    echo $key . ' => ' . $value . "\n";
}



Output