Home  >  Article  >  Backend Development  >  Simple example of PHP generator_PHP tutorial

Simple example of PHP generator_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 09:53:52950browse

A simple example of PHP generator

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 generated

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/1000079.htmlTechArticle Simple Example of PHP Generator This article mainly introduces a simple example of PHP Generator. This article explains the range and xrange functions Basic usage examples, friends in need can refer to it. Generally, you are iterating...
Statement:
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