Simple example of PHP generator, php generator_PHP tutorial

WBOY
Release: 2016-07-13 09:53:52
Original
1404 people have browsed it

Simple example of PHP generator, php generator

Generally 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. , or even cause insufficient memory.
Copy code 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 For example, only the intermediate variable $i
will be generated Copy code The 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 ";
}

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/998817.htmlTechArticleA simple example of PHP generator, PHP generator Generally, when you iterate a set of data, you need to create a piece of data. If the array is large, it will consume a lot of performance and even cause insufficient memory. ...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template