🔁 PHP Control Flow & Logic
Estimated reading: 3 minutes 119 views

🔄 PHP Iterables – Looping Through Arrays, Objects & Generators

Master the concept of iterables in PHP, including arrays, objects, and the powerful Traversable interface.


🧲 Introduction – What Are Iterables in PHP?

An iterable in PHP refers to any value that can be looped over using foreach. This includes traditional arrays, objects that implement the Traversable interface (like Iterator and Generator), and anything defined as iterable in type declarations.

🎯 In this guide, you’ll learn:

  • What qualifies as an iterable in PHP
  • Differences between arrays and objects as iterables
  • How to create custom iterable classes
  • How generators simplify custom iteration
  • Iterable type hinting (PHP 7.1+)

✅ Basic Iterable – Array

$names = ["Alice", "Bob", "Charlie"];

foreach ($names as $name) {
    echo $name . "<br>";
}

🔍 Output:

Alice
Bob
Charlie

📘 Arrays are the most common and default iterable in PHP.


🧑‍💻 Iterable Object – Using Traversable

Objects can be made iterable by implementing the Iterator or IteratorAggregate interface.

Example – Using IteratorAggregate

class Team implements IteratorAggregate {
    private $members = ["Alice", "Bob", "Charlie"];

    public function getIterator(): Traversable {
        return new ArrayIterator($this->members);
    }
}

$team = new Team();

foreach ($team as $member) {
    echo "$member <br>";
}

🔍 Output:

Alice
Bob
Charlie

📘 Traversable is the base interface for all iterable objects.


⚙️ Iterable Type Hinting (PHP 7.1+)

function printItems(iterable $data) {
    foreach ($data as $item) {
        echo "$item <br>";
    }
}

printItems(["red", "green", "blue"]);

📘 Use iterable as a parameter or return type to accept both arrays and Traversable objects.


🔁 Generator Function – Lightweight Iterables

Generators let you yield values lazily without creating arrays manually.

function countToThree() {
    yield 1;
    yield 2;
    yield 3;
}

foreach (countToThree() as $number) {
    echo $number . " ";
}

🔍 Output: 1 2 3

📘 Memory-efficient way to build iterables on the fly.


🔄 Comparing Iterables in PHP

TypeIterable?Description
array✅ YesNative PHP iterable
Generator✅ YesYields values using yield
Iterator✅ YesInterface that supports iteration
Traversable✅ YesBase for all objects usable in foreach
stdClass❌ NoNot iterable unless cast to array
string❌ NoNot iterable in foreach

🧠 Best Practices

  • ✅ Use iterable type hints when accepting arrays or generators
  • ✅ Use generators for performance when working with large datasets
  • ✅ Implement IteratorAggregate for simple custom iterable classes
  • ❌ Avoid using non-iterable types in foreach (e.g., strings, integers)

📌 Summary – Recap & Next Steps

PHP iterables allow you to loop through data efficiently and flexibly, whether it’s an array, a generator, or a custom object.

🔍 Key Takeaways:

  • All arrays and Traversable objects are iterable
  • Use foreach to iterate over any iterable
  • Type hint with iterable for broad compatibility
  • Use generators to improve memory usage

⚙️ Real-World Use Cases:
Looping over datasets, building collections, processing files, implementing custom data structures.


❓ Frequently Asked Questions (FAQs)

❓ What data types are iterable in PHP?
✅ Arrays, Generator, and any object implementing Traversable (Iterator, IteratorAggregate).

❓ What is the difference between Traversable and iterable?
Traversable is an interface. iterable is a broader type hint introduced in PHP 7.1 that accepts arrays and any Traversable.

❓ Can I use iterable as a return type?
✅ Yes, like this:

function getData(): iterable { return [1, 2, 3]; }

❓ Are strings iterable in PHP?
❌ No. foreach cannot iterate over strings unless converted to arrays.


Share Now :
Share

🔄 PHP — Iterables

Or Copy Link

CONTENTS
Scroll to Top