Home > Article > Backend Development > Simple example of PHP generator_PHP tutorial
This article mainly introduces a simple example of PHP generator. This article explains the basic usage examples of range and xrange functions. Friends in need can refer to the following
Usually when you iterate a set of data, you need to create a data. If the array is large, it will consume a lot of performance and even cause insufficient memory.
The code is as follows:
//Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in E:phptestindex.php on line 5
range(1, 100000000);
PHP5.5 implements a generator. Whenever an array element is generated, it is returned with the yield keyword, and the execution function is paused. When the function next method is executed, execution will continue from the last yielded position, as follows Example, only intermediate variable $i
will be generatedThe code is as follows:
Function xrange($start, $limit, $step = 1) {
for ($i = $start; $i <= $limit; $i = $step) {
yield $i;
}
}
foreach (xrange(1, 9, 1) as $number) {
echo "$number ";
}