
- PHP 7 Tutorial
- PHP 7 - Home
- PHP 7 - Introduction
- PHP 7 - Performance
- PHP 7 - Environment Setup
- PHP 7 - Scalar Type Declarations
- PHP 7 - Return Type Declarations
- PHP 7 - Null Coalescing Operator
- PHP 7 - Spaceship Operator
- PHP 7 - Constant Arrays
- PHP 7 - Anonymous Classes
- PHP 7 - Closure::call()
- PHP 7 - Filtered unserialize()
- PHP 7 - IntlChar
- PHP 7 - CSPRNG
- PHP 7 - Expectations
- PHP 7 - use Statement
- PHP 7 - Error Handling
- PHP 7 - Integer Division
- PHP 7 - Session Options
- PHP 7 - Deprecated Features
- PHP 7 - Removed Extensions & SAPIs
- PHP 7 Useful Resources
- PHP 7 - Quick Guide
- PHP 7 - Useful Resources
- PHP 7 - Discussion
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
- Related Articles
- Iterables in Dart Programming
- PHP php://
- Upload file with php to another php server
- PHP Generators.
- PHP Overloading
- PHP Traits
- PHP $_GET
- PHP $GLOBALS
- PHP $_SERVER
- PHP superglobals
- PHP References
- PHP Constants
- PHP Expressions
- PHP Tags
- PHP NULL
