Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP Iterables
From PHP 7.1 onwards, PHP provides a pseudo-type called iterable that accepts any object implementing the Traversable interface, including arrays. This type declaration ensures parameters can be used with foreach loops or generator functions.
Syntax
A function can declare iterable as a parameter type to accept values usable in foreach statements. If the parameter doesn't support iteration, PHP throws a TypeError −
function functionName(iterable $parameter): iterable {
// Function body
}
Example with Array Parameter
This example shows how to use iterable as a function parameter type ?
<?php
$languages = array("PHP", "Java", "Python");
function displayLanguages(iterable $langs) {
foreach ($langs as $lang) {
echo $lang . "<br>";
}
}
displayLanguages($languages);
?>
PHP Java Python
Function Returning Iterable
Functions can also return iterable data types. Use is_iterable() to verify the return type ?
<?php
function createNumbers(): iterable {
$numbers = [];
for ($i = 1; $i < 4; $i++) {
$numbers[$i] = $i * 2;
}
return $numbers;
}
$result = createNumbers();
var_dump(is_iterable($result));
// Display the actual values
foreach ($result as $key => $value) {
echo "Index $key: $value<br>";
}
?>
bool(true) Index 1: 2 Index 2: 4 Index 3: 6
Generator with Iterable Return Type
Generators are also considered iterable and can be type-hinted accordingly ?
<?php
function numberGenerator(): iterable {
yield 1;
yield 2;
yield 3;
}
foreach (numberGenerator() as $number) {
echo "Generated: $number<br>";
}
?>
Generated: 1 Generated: 2 Generated: 3
Error Handling
Passing a non-iterable value to an iterable parameter throws a TypeError ?
<?php
function processIterable(iterable $data) {
foreach ($data as $item) {
echo $item . "<br>";
}
}
try {
processIterable("not iterable"); // This will throw TypeError
} catch (TypeError $e) {
echo "Error: " . $e->getMessage();
}
?>
Error: Argument 1 passed to processIterable() must be iterable, string given
Conclusion
The iterable pseudo-type provides type safety for functions working with arrays, iterators, and generators. It ensures parameters support foreach loops and helps catch type errors early in development.
