PHP Iterable

Last updated on

The first appearance of PHP iterable was in PHP version ( 7.1 ) – Iterables are a powerful feature in PHP that allow you to work with collections of data in a flexible and efficient manner.

In this article, we will explore the concept of iterables, how they work, and how you can use them in your PHP projects.

What are Iterables?

In PHP, an object that can be used in a foreach loop is known as an iterable. This includes arrays, objects that implement the Traversable interface, and generators.

For example, consider the following array:

<?php 
   $fruits = ['apple', 'banana', 'cherry'];
?>

This is an iterable because it can be used in a foreach loop:

<?php 
   foreach ($fruits as $fruit) {
    echo $fruit;
   }
?>

This code will output the following:

apple
banana
cherry

In addition, the term “iterable” is used to describe a data type that can be looped over, or iterated. When you iterate over an iterable data type, you can access each of its elements or values in turn, one at a time. This allows you to process or manipulate the data in a structured and organized way.

Here’s an example of how to use an iterable data type in PHP:

<?php
function printIterable(iterable $iterable) {
    foreach ($iterable as $key => $value) {
        echo "$key: $value\n";
    }
}

$fruits = ['apple', 'banana', 'cherry', 'date'];
printIterable($fruits);

In this code, the printIterable() function takes an iterable data type as its parameter, and iterates over it using a foreach loop. The function then prints each key-value pair to the screen using the echo statement.

Note that the iterable type hint is used in the function parameter to specify that the function expects an iterable data type.

This technique is beneficial as it ensures that the function receives the appropriate data type, which can minimize errors and bugs in your code.

How do Iterables Work?

Iterables are essentially a way of abstracting over collections of data. When you use a foreach loop with an iterable, PHP will automatically iterate over the elements of the iterable and execute the loop body for each element.

For example, consider the following code:

<?php 
   $numbers = [1, 2, 3];

   foreach ($numbers as $number) {
      echo $number * 2;
   }
?>

This code will output the following:

2
4
6

In this code, the foreach loop iterates over the elements of the $numbers array and multiplies each element by 2.

How to Work with Iterables in PHP

There are a number of built-in functions in PHP that allow you to work with iterables in various ways. Some of the most commonly used functions include:

  • foreach: This is the most basic way to work with iterables. It allows you to iterate over the elements of an iterable and execute a loop body for each element.
  • count: This function returns the number of elements in an iterable.
  • array_map: This function applies a callback function to each element of an iterable and returns a new iterable containing the modified elements.
  • array_filter: This function applies a callback function to each element of an iterable and returns a new iterable containing only the elements for which the callback function returns true.

For example, consider the following code:

<?php 
   $numbers = [1, 2, 3];

   $result = array_map(function ($number) {
      return $number * 2;
   }, $numbers);

   foreach ($result as $number) {
      echo $number;
   }
?>

This code will output the following:

2
4
6

In this code, the array_map function is used to multiply each element of the $numbers array by 2. You can use a foreach loop to iterate over the resulting iterable and output each element.

Traversable interface

To implement the Traversable interface in your object, you need to implement a set of methods that PHP uses to iterate over the object. These methods include rewind()valid()current()next(), and key(). Let’s take a closer look at each of these methods:

  • rewind(): This method is called when the foreach loop starts. It resets the internal pointer of the iterable so that the first element can be retrieved. This method should return void.
  • valid(): This method is called at the beginning of each iteration to determine whether the current element is valid. This method should return a boolean value (true if the current element is valid, false otherwise).
  • current(): This method is called to retrieve the current element of the iterable. This method should return the current element.
  • next(): This method is called at the end of each iteration to move the internal pointer to the next element. This method should return void.
  • key(): This method is called to retrieve the key of the current element. This method should return the key.

Here is an example implementation of these methods in a custom iterable object:

<?php 
   class Book implements \Iterator {
      
      private $pages = [];
      private $position = 0;

      public function addPage( $content )
      {
         $this->pages[] = $content;
      }

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

      public function valid() {
         return isset($this->pages[$this->position]);
      }

      public function current() {
         return $this->pages[$this->position];
      }

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

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

With these methods implemented, you can use the Book object in a foreach loop like so:

<?php 

   $book = new Book();
   $book->addPage("Page 1");
   $book->addPage("Page 2");
   $book->addPage("Page 3");

   foreach ($book as $key => $page) {
       echo "$key: $page\n";
   }

?>

This code will output the following:

0: Page 1
1: Page 2
2: Page 3

In this code, the Book object is used in a foreach loop to iterate over its pages. The rewind()valid()current()next(), and key() methods are used by PHP to traverse the object’s pages and retrieve their content and position.

Wrapping Up

In PHP, iterable data types provide a convenient way to loop over and manipulate complex data structures. Whether you’re working with arrays, objects, or generators, the ability to iterate over data in a structured and organized way can make your code more efficient and easier to understand.

Implementing the Traversable interface in PHP enables you to customize the way your objects are iterated over, giving you greater flexibility and control when manipulating data. This feature makes the Traversable interface a powerful tool for creating iterable objects in PHP.

In summary, you have learned how to effectively use iterable data types in PHP, with examples provided for both arrays and objects.

Share on: