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 ";
}