PHP Iterables


PHP - What is an Iterable?

Iterable is any value that can be helped by the foreach() loop.

Iterable pseudo-type is introduced in PHP 7.1, and can be used as a type of job dispute data and job return values.


PHP - Using Iterables

The iterable keyword can be used as a type of work dispute data or as a type of job return:


Example

Use an iterable function argument:

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

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


Example

Return an iterable:

<?php
function getIterable():iterable {
  return ["a", "b", "c"];
}

$myIterable = getIterable();
foreach($myIterable as $item) {
  echo $item;
}
?>


PHP - Creating Iterables

Arrays

All the same members are iterable, so any similar members can be used as an argument for work that needs to be repeated.

Iterators

Any object using an Iterator interface can be used as an argument for work that needs to be duplicated.

The iterator contains a list of items and provides access to them. Saves the reference to one of the items in the list. Each item listed must have a key that can be used to find the item.

The repeater must have the following characteristics:

  • current() - Returns the current point the cursor is pointing to. It can be any kind of data
  • key() Returns the key associated with the current feature in the list. It can be a whole number, float, boolean or just a unit of characters
  • next() - Moves the cursor to the next part in the list
  • rewind() Moves the cursor to the first item in the list
  • valid() If the internal identifier does not point to any object (for example, if next () called at the end of the list), this should also be false. It returns the truth to any other story

Example

Implement the Iterator interface and use it as an iterable:

<?php
// Create an Iterator
class MyIterator implements Iterator {
  private $items = [];
  private $pointer = 0;

  public function __construct($items) {
    // array_values() makes sure that the keys are numbers
    $this->items = array_values($items);
  }

  public function current() {
    return $this->items[$this->pointer];
  }

  public function key() {
    return $this->pointer;
  }

  public function next() {
    $this->pointer++;
  }

  public function rewind() {
    $this->pointer = 0;
  }

  public function valid() {
    // count() indicates how many items are in the list
    return $this->pointer < count($this->items);
  }
}

// A function that uses iterables
function printIterable(iterable $myIterable) {
  foreach($myIterable as $item) {
    echo $item;
  }
}

// Use the iterator as an iterable
$iterator = new MyIterator(["a", "b", "c"]);
printIterable($iterator);
?>