Start Coding

Topics

PHP Iterables

In PHP, an iterable is any value that can be looped through with a foreach loop. Iterables provide a convenient way to work with collections of data, such as arrays and objects implementing the Traversable interface.

Understanding Iterables

Iterables are essential for processing collections of data efficiently. They allow you to iterate over elements without needing to know the internal structure of the collection. This abstraction simplifies code and improves flexibility.

Types of Iterables

  • Arrays
  • Objects implementing the Traversable interface

Using Iterables with foreach Loops

The most common way to work with iterables is through the foreach loop. This construct allows you to iterate over each element in the collection easily.

Example: Iterating Over an Array


$fruits = ["apple", "banana", "cherry"];
foreach ($fruits as $fruit) {
    echo $fruit . "\n";
}
    

This code will output each fruit on a new line.

Example: Iterating Over an Object

For objects, you need to implement the Iterator interface or use generators to make them iterable.


class FruitBasket implements Iterator {
    private $fruits = ["apple", "banana", "cherry"];
    private $position = 0;

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

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

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

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

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

$basket = new FruitBasket();
foreach ($basket as $fruit) {
    echo $fruit . "\n";
}
    

Benefits of Using Iterables

  • Simplified code for working with collections
  • Improved readability and maintainability
  • Abstraction of data structure details
  • Compatibility with built-in PHP functions that accept iterables

Iterable Type Hint

PHP 7.1 introduced the iterable type hint, allowing you to specify that a function parameter or return value should be iterable.


function printItems(iterable $items) {
    foreach ($items as $item) {
        echo $item . "\n";
    }
}

$array = [1, 2, 3];
printItems($array);
    

Related Concepts

To deepen your understanding of PHP iterables and related topics, explore these concepts:

Mastering iterables in PHP will enhance your ability to work with collections efficiently, leading to more elegant and maintainable code.