What is a Generator function?
The Generator function is effectively a more compact and efficient way to write an Iterator. It allows you to define a function (your xrange), to calculate and return values while you are in loop:
foreach (xrange(1, 10) as $key => $value) {
echo "$key => $value", PHP_EOL;
}
Exit:
0 => 1
1 => 2
...
9 => 10
Since there is no support for older versions, I can do it with "normal functions"??
Now you may wonder why not just use "Old and good native range " to reach that exit. And you’re right. The exit would be the same. The difference is how we get there.
When we use range
, this will run the entire array of numbers in memory and return the entire array to the foreach
which will then provide the values. In other words, the foreach
operate in the matrix itself. The range
and the foreach will only "chat" once. Think of it as getting a package at the post office. The courier will deliver the package to you and leave. And then you unwrap the whole package, taking out everything that is inside.
Examples:
<?php
// array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12)
foreach (range(0, 12) as $number) {
echo $number;
}
// The step parameter
// array(0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100)
foreach (range(0, 100, 10) as $number) {
echo $number;
}
// Usage of character sequences
// array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i');
foreach (range('a', 'i') as $letter) {
echo $letter;
}
// array('c', 'b', 'a');
foreach (range('c', 'a') as $letter) {
echo $letter;
}
?>
This answer does not seem to answer the question, I see in it no way to simulate a Generator, only an explanation about what is a.
– BrunoRB