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 looping:
foreach (xrange(1, 10) as $key => $value) {
echo "$key => $value", PHP_EOL;
}
Output:
0 => 1
1 => 2
...
9 => 10
Since old versions are not supported, can I do it with "normal" functions ??
Now you may wonder why not just use "Old and good native range" to reach this exit. And you are right. The output would be the same. The difference is how we got there .
When we use range
, this will execute the entire array of numbers in memory and return the entire array to the foreach
which will then supply the values. In other words, foreach
will operate in the array itself. The range
and foreach will only "chat" once. Think of it as getting a package at the post office. The deliveryman will deliver you the package and leave. And then you unwrap the entire package, taking everything in.
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;
}
?>