PHP Iterables

🔁 PHP Iterables

In PHP, iterable means anything that can be looped using foreach.

PHP introduced the iterable type (PHP 7.1+) to accept:

✔ Arrays
✔ Traversable Objects (Iterator, Generator, etc.)

If a variable can be used in foreach, PHP calls it iterable.


1️⃣ What is an Iterable?

Any of the following:

✔ Array

✔ Object implementing Traversable

✔ Generator

All these can be used with foreach.
Therefore, they are iterables.


2️⃣ Using iterable as a Type Hint

You can define a function that accepts any iterable:

Works with both arrays & generators:


3️⃣ Returning an Iterable


 


4️⃣ Iterable with Generators (Very Important)

Generators allow you to create lazy-loaded, memory-efficient iterables.


 

Output:

1 2 3

5️⃣ Iterable with Objects (Iterator Interface)


 


6️⃣ Why Use Iterable Type?

✔ Accepts both arrays + Traversable objects
✔ More flexible than array type
✔ Used in modern PHP libraries
✔ Useful for dependency injection
✔ Great for reading large files with generators
✔ Helps make functions truly generic


7️⃣ Checking if Something is Iterable

 


🎯 Summary (Easy to Remember)

Concept Meaning
iterable Anything you can loop using foreach
Accepts Arrays + Traversable (Generators, Iterators)
Type hint function test(iterable $x)
Return type : iterable
Check is_iterable()

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *