Generators are functions that provide a simple way to loop through data without the need to build an array in memory. “yield” is the main command here.
function getRange ($max = 10) { for ($i = 1; $i < $max; $i++) { yield $i; } } foreach (getRange(PHP_INT_MAX) as $range) { echo "Dataset {$range}
"; }
Dissecting the getRange function, this time, we only loop through the values and yield an output. yield is similar to return as it returns a value from a function, but the only difference is that yield returns a value only when it is needed and does not try to keep the entire dataset in memory.
Why we use generators?
There are times when we might want to parse a large dataset (it can be log files), perform computation on a large database result, etc. We don’t want actions like this hogging all the memory. We should try to conserve memory as much as possible. The data doesn’t necessarily need to be large — generators are effective no matter how small a dataset is.
Generators can be key-value too :
function getRange ($max = 10) { for ($i = 1; $i < $max; $i++) { $value = $i * mt_rand(); yield $i => $value; } }
Generators can also take in values. This means that generators allow us to inject values into them. For example, we can send a value to our generator telling to stop execution or change the output.
function getRange ($max = 10) { for ($i = 1; $i < $max; $i++) { $injected = yield $i; if ($injected === 'stop') return; } } $generator = getRange(PHP_INT_MAX); foreach ($generator as $range) { if ($range === 10000) { $generator->send('stop'); } echo "Dataset {$range}
"; }