Simple PHP generator instance, php Generator

Source: Internet
Author: User

Simple PHP generator instance, 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, and even cause insufficient memory.
Copy codeThe Code is as follows:
// Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes) in E: \ php \ test \ index. php on line 5
Range (1, 100000000 );

PHP5.5 implements the generator. Every time an array element is generated, it is returned with the yield keyword, And the execution function is paused. When the next method is executed, it will continue to be executed from the last position where yield is located, in the following example, only the intermediate variable $ I is generated.
Copy codeThe 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 ";
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.