What is an Iterable in PHP?

In PHP, an iterable is any value that can be looped through using a foreach loop.
It includes arrays and objects that implement the Traversable interface, like Iterator or Generator.
You can use iterable as a function parameter or return type to enforce that only iterable values are allowed.
This helps write more type-safe and flexible code.
The iterable pseudo-type was introduced in PHP 7.1.

PHP Iterable Example

📄 File Name: iterable-example.php


<?php
function printItems(iterable $items) {
    foreach ($items as $item) {
        echo $item . PHP_EOL;
    }
}

// Example with array
$names = ['Priya', 'John', 'Kumar'];
printItems($names);

// Example with Generator
function generateItems() {
    yield 'One';
    yield 'Two';
    yield 'Three';
}
printItems(generateItems());
?>

Notes:

  • iterable was introduced in PHP 7.1 as a pseudo-type
  • You can use it as a function parameter type or return type

Example with return type:


function getItems(): iterable {
    return ['A', 'B', 'C'];
}

Summary

Feature Details
What is iterable Arrays or objects you can foreach
Introduced in PHP 7.1
File to create iterable-example.php
Usage Function parameters and return types