PHP yield

Updated: 12 January 2025

  • Any function containing yield is a generator function.
  • When a generator function is called, it returns an iterable object.
  • Effectively, yield pauses execution of the enclosing generator function until next required.
<?php

declare(strict_types=1);

function gen_values(): iterable {
    yield '1st';
    yield '2nd';
    yield from ['3rd', '4th'];
    yield '5th';
}

foreach (gen_values() as $val) {
    echo $val . PHP_EOL;
}

/*
1st
2nd
3rd
4th
5th

Leave a comment