Generator in PHP

Introduction

This article explains Generators in PHP. Generators provide simple iterations without the overhead or complexity of implementing a category that implements the Iterator interface. A generator permits you to write code that uses foreach to iterate over a group of information without the necessity of creating an associated array in memory, that may cause you to exceed a memory limit, or that needs a substantial quantity of processing time to get. Instead, you'll be able to write a generator function, that is the same as a traditional function, except that rather than returning once, a generator will yield persistently because it is intended to produce the values to be iterated over.

A generator function appearance rather like a standard function, except that rather than returning a value, a generator yields as several values because it must. When a generator function is called, it returns the associated object that will be iterated over. When you iterate over that object (for instance, via a foreach loop), PHP can determine the generator function each time it wants a value, then saves the state of the generator once the generator yields a value so it is often resumed once succeeding values is needed. A generator cannot return a value; doing so will result in a compile error.

<?php

function gen_count() {

    for ($a = 1; $a <= 5; $a++) {

        yield $a;

    }

}

$Gen_value= gen_count();

foreach ($Gen_valu as $v) {

    echo "$v"."<br>";

}

?>
 

Yielding a key/value pair


<?php

$type = <<<'EOF'

a;java;likes oops pattern

b;php;php is a open source

c;Zend;zend is framework

EOF;

 

function exchange_input($type) {

    foreach (explode("<br>", $type) as $line) {

        $field_name = explode('|', $line);

        $id = array_shift($field_name);

 

        yield $id => $field_name;

    }

}

foreach (exchange_input($type) as $id => $field_name) {

    echo "$id:<br>";

    echo "    $field_name[0]<br>";

    echo "    $field_name[1]<br>";

}

?>

 

Implement range generator

 

<?php

function oddrange($begining, $control, $Steps = 1) {

if ($beginning < $control) {

        if ($Steps <= 0) {

            throw new LogicException('must be positive');

        }

        for ($a = $begining; $a <= $control; $a += $Steps) {

            yield $a;

        }

    } else {

        if ($Steps >= 0) {

            throw new LogicException('must be negative');

        }

        for ($a = $beginning; $a >= $control; $a += $Steps) {

            yield $a;

        }

    }

}

echo 'odd no range():  ';

foreach (range(1, 9, 2) as $num) {

    echo "$num ";

}

echo "<br>";

echo 'odd no for oddrange(): ';

foreach (oddrange(1, 9, 2) as $num) {

    echo "$num";

}

?>


Similar Articles