PHP Generator Simple example, PHP generator _php Tutorial

Source: Internet
Author: User

PHP Generator Simple instance, PHP generator


Generally when you iterate over a set of data, you need to create a data, assuming that the array is large, it consumes a lot of performance, or even causes memory shortage.
Copy the Code code as follows:
Fatal error:allowed memory size of 134217728 bytes exhausted (tried to allocate + bytes) in E:\php\test\index.php on L INE 5
Range (1, 100000000);

PHP5.5 implements the generator, each time an array element is returned with a yield keyword, and the execution function is paused, and when the function next method is executed, it proceeds from the last yield position, as shown in the following example, only intermediate variables are generated $i
Copy the Code code 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";
}

http://www.bkjia.com/PHPjc/998817.html www.bkjia.com true http://www.bkjia.com/PHPjc/998817.html techarticle PHP Generator Simple example, PHP generator generally when you iterate a set of data, you need to create a data, assuming that the array is large, it will consume a lot of performance, or even cause memory shortage. ...

  • 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.