PHP Tutorial Tutorials - PHP Iterables

PHP Iterables

Iterables is a new type in PHP7.1+.

Iterable parameter type

Iterable can be used as a parameter type to indicate that a function requires an array or instance of Traversable.

<?php
function iterable(iterable $iterable) {
    foreach ($iterable as $value) {
        echo $value.PHP_EOL;
    } 
}

$data = array(1,2,3,4,5);
iterable($data);
?>

Output

1
2
3
4
5

Iterable return type

Iterable can also be used as a return type to indicate a function will return an iterable value.

<?php
function bar(): iterable {
    return [1, 2, 3];
}

$arr = bar();
foreach ($arr as $value) {
    echo $value.PHP_EOL;
} 
?> 

Iterable generator return type

Functions declaring iterable as a return type may also be generators.

<?php
function gen(): iterable {
    yield 1;
    yield 2;
    yield 3;
}
$res = gen();
var_dump($res); // a generator object implementing the Traversable interface.
                // so it's iterable using foreach
foreach($res as $value){
    echo $value.PHP_EOL;
}
echo PHP_EOL;

$generator = gen(); // $generator is an generator object 
while( $generator->valid()){
  echo $generator->current().PHP_EOL;
  $generator->next();
}
?>
object(Generator)#1 (0) { }
1
2
3

1
2
3
Date:2019-10-01 01:01:06 From:www.Lautturi.com author:Lautturi