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

";
   }
}
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

Output

This will produce following result −

bool(true)

Following is an example of generator with iterable return type

Example

PHP Version

Iterable pseudo-type was introduced in PHP 7.1

Updated on: 2020-09-19T14:41:10+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements