Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
PHP Iterables
Definition and Usage
From version 7.1 onwards, PHP provides a new pseudo-type called iterable. Any object (such as array) that implements Traversable interface is acceepted by it. This type uses foreach construct or a generator function that yields one value at a a time.
Syntax
A function can have iterable as type of its parameter to let the function accept a set of values used in foreach statement. If the parameter doesn't support foreach loop, PHP parser throws TypeError
Example
<?php
$arr1=array("PHP","Java","Python");
function myfunc (iterable $arr1){
foreach ($arr1 as $lang){
echo $lang . "
";
}
}
myfunc($arr1);
?>
Output
This will produce following result −
PHP Java Python
A PHP function can also return an iterable data type such as array. We use is_iterable() function to verify type of returned value.
Example
<?php
function newfunc ():iterable{
$arr2=[];
for ($i=1;$i<4;$i++){
$arr2[$i]=$i*2;
}
return $arr2;
}
$ret=newfunc();
var_dump (is_iterable($ret));
?>
Output
This will produce following result −
bool(true)
Following is an example of generator with iterable return type
Example
<?php
function gen(): iterable {
yield 1;
yield 2;
yield 3;
}
gen();
?>
PHP Version
Iterable pseudo-type was introduced in PHP 7.1