Iterables in PHP

Looping for PHP
Time and date in PHP

What is an Iterable in PHP?

An iterable is a value that can be iterated over. It’s an excellent option for keeping track of how many times you’ve gone through a loop. For example, if you wish to exit a loop after 10 iterations, you may simply do it using an iterable.

How to use Iterables in PHP

  • An iterable is any value which is accepted by a foreach loop.
  • PHP 7.1 introduced this pseudo-data type and it can be used as the return data type of functions. Also, the function can accept iterables as its argument.

Iterables give a simple method to keep track of the iteration count while dealing with loops, which might be handy in certain scenarios. It may also be used as a function’s return type, and the function can take iterables as arguments.

How to check if an object is iterable

To determine if an object is an instance of the IteratorAggregate or Iterator interfaces, use the instanceof operator. As an example:

$obj = new MyClass();
if ($obj instanceof IteratorAggregate || $obj instanceof Iterator) {
  // object is iterable
}

How to Loop over an Iterable Object

You can use the foreach loop to loop over an iterable object. For example:

$iterable = new MyIterableClass();
foreach ($iterable as $value) {
  // do something with $value
}

Creating your own Iterable class

You must implement the IteratorAggregate interface and specify the getIterator function to construct your own iterable class. As an example:

class MyIterableClass implements IteratorAggregate {
  private $data = array();
  
  public function __construct($data) {
    $this->data = $data;
  }
  
  public function getIterator() {
    return new ArrayIterator($this->data);
  }
}

Q&A

Q: What are the different types of iterables in PHP?
A: Arrays, objects that implement the Iterator interface, and objects that implement the Traversable interface are all examples of iterables in PHP.

Q: Can you explain the difference between Iterator and Traversable interfaces?
A: The Iterator interface offers a collection of methods for iterating through an object, such as rewind, current, key, next, and valid. The Traversable interface, on the other hand, merely says that a class is traversable and does not require any specific methods to be implemented. Iterator-implemented classes must also implement the Traversable interface.

Q: What is the use of IteratorAggregate interface?
A: The IteratorAggregate interface allows you to iterate over an object by establishing an external iterator object that can traverse the item’s contents. This enables the object to create its own traversal method without needing to implement the Iterator interface. Classes that implement this interface must specify a single method called getIterator, which returns an instance of an Iterator interface object.

Q: What is the difference between foreach and for loop when using iterators?
A: The foreach loop is specifically designed to work with iterators, it automatically calls the rewind method at the beginning of the loop and the valid method to check if there are more elements to iterate over.

The for loop can also be used with iterators, but requires the programmer to manually call the rewind, valid, current, key, and next methods at the appropriate points in the loop.

Q: How to use Iterator with Closure?
A: Closures can be used as iterators in PHP. To do this, create an instance of the IteratorIterator class and feed it your closure as an argument. The closure should take no parameters and return an array containing the current key and value. To make the external variables available inside the closure, the closure should additionally include a use statement.

$myArray = [1, 2, 3, 4];
$iter = new IteratorIterator(new ArrayIterator($myArray));
foreach ($iter as $key => $val) {
    echo $val . PHP_EOL;
}

Here, IteratorIterator class is used to iterate over the ArrayIterator class which is then passed the closure function.

Exercises:

  1. What are iterables in PHP?
  2. How do you iterate over an array using a for loop in PHP?
  3. How do you iterate over an array using a foreach loop in PHP?
  4. How do you iterate over an object using a foreach loop in PHP?
  5. How do you create an iterator for a custom class in PHP?
  6. How do you use the yield keyword to create a generator function in PHP?

Answers:

  1. An iterable is an object that can be iterated (looped) over, such as an array or an object.
  2. for ($i = 0; $i < count($array); $i++) { // code to be executed; }
  3. foreach ($array as $value) { // code to be executed; }
  4. foreach ($object as $property => $value) { // code to be executed; }
  5. To create an iterator for a custom class, the class must implement the Iterator interface and define the rewind, valid, current, key, and next methods.
  6. function generator() { yield $value1; yield $value2; }
Looping for PHP
Time and date in PHP

Stay up-to-date about PHP!

We don’t spam!

en English
X
Scroll to Top