Curriculum
Course: PHP Basic
Login

Curriculum

PHP Basic

PHP Install

0/1

PHP Casting

0/1

PHP Constants

0/1

PHP Magic Constants

0/1

PHP Operators

0/1

PHP Reference

0/276
Text lesson

PHP Iterables

PHP – What is an Iterable?

An iterable is any value that can be looped through with a foreach() loop. Introduced in PHP 7.1, the iterable pseudo-type can be used for function arguments and return values.

PHP – Using Iterables

The iterable keyword can be used as a data type for function arguments or as a return type for functions.

Example

Use iterable as a type for a function argument to accept any value that can be looped through with a foreach() loop.

<?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 arrays in PHP are iterables, meaning they can be used as arguments for functions that accept iterables.

Iterators: Any object implementing the Iterator interface can serve as an argument for functions requiring an iterable. An iterator maintains a list of items with a pointer to one of the elements and provides methods for traversal.

A valid iterator must implement these methods:

  • current(): Returns the current element pointed to by the iterator, which can be of any data type.
  • key(): Returns the key associated with the current element. The key must be an integer, float, boolean, or string.
  • next(): Moves the pointer to the next element in the list.
  • rewind(): Resets the pointer to the first element in the list.
  • valid(): Returns false if the pointer is not pointing to any element (e.g., after next() is called at the end), and true otherwise.

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);
?>