×

php · level 3 · unit 7 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

A hands out values one at a time, pausing in between.

A function that returns an array must build all of it first. A million rows means a million rows held at once. A generator is instead: each hands out one value and pauses the function right there, until the loop asks for the next.

Write yield instead of return and PHP turns the function into a generator. Calling it runs nothing yet. It hands back a Generator object, and foreach pulls the values out one by one. That makes it perfect for reading a big file line by line with fopen and fgets.

<?php
function lines(string $path): Generator {
    $file = fopen($path, "r");
    $line = fgets($file);
    while ($line !== false) {
        yield trim($line);
        $line = fgets($file);
    }
    fclose($file);
}
$path = sys_get_temp_dir() . "/shopping.txt";
file_put_contents($path, "milk\neggs\nbread\n");
foreach (lines($path) as $item) {
    echo "Buy $item\n";
}

fopen opens the file for reading, fgets reads one line or gives false at the end, and fclose closes it.