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

 Live Demo

<?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

 Live Demo

<?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

Updated on: 19-Sep-2020

622 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements