Using the PHP yield Keyword for Memory‑Efficient Data Processing

This article explains how the PHP yield keyword creates generators that allow lazy iteration over large data sets, large files, or infinite sequences, reducing memory consumption and improving performance by pausing and resuming function execution without returning the entire collection at once.

php Courses
php Courses
php Courses
Using the PHP yield Keyword for Memory‑Efficient Data Processing

The yield keyword in PHP can be used to optimise memory usage when you need to iterate over large data sets.

Unlike return, yield returns a value without terminating the function, allowing the function to be resumed later from the point where it was paused.

For example, the following function uses yield to iterate over a numeric array:

function getNumbers() {
  $numbers = [1, 2, 3, 4, 5];

  foreach ($numbers as $number) {
    yield $number;
  }
}

This function does not create an actual array of numbers; instead, it creates a generator object that tracks only the current number during iteration, so the whole array does not need to be stored in memory.

You can traverse the generator object with a foreach loop:

foreach (getNumbers() as $number) {
  echo $number;
}

This code prints the numbers 1, 2, 3, 4 and 5.

The yield keyword can be used in many scenarios to optimise memory usage, such as iterating large data sets, processing large files, or generating numeric sequences.

Additional considerations when using yield:

It can only be used inside functions.

It can be used to return multiple values from a function.

It can pause and resume function execution.

To use yield, simply place it before the value you want to return from the function, as shown in the earlier example.

Benefits of using yield include:

Improved performance by avoiding loading the entire data set at once.

Reduced memory usage by tracking only the current state of the generator.

Flexibility for implementing lazy loading, streaming, and infinite sequences.

Typical use cases for yield are:

Iterating large data sets without storing the whole collection in memory.

Processing large files without loading the entire file into memory.

Generating sequences on‑the‑fly without pre‑computing the entire list.

Examples:

Iterating a database result set

function getProducts() {
  $db = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

  $stmt = $db->query('SELECT * FROM products');

  while ($row = $stmt->fetch()) {
    yield $row;
  }
}

foreach (getProducts() as $product) {
  echo $product['name'];
}

This code iterates all products and prints each name without loading the entire result set into memory.

Processing a large CSV file

function processCsvFile($filename) {
  $file = fopen($filename, 'r');

  while (($row = fgetcsv($file)) !== false) {
    yield $row;
  }

  fclose($file);
}

foreach (processCsvFile('my_file.csv') as $row) {
  // process each CSV row
}

The CSV is processed line‑by‑line, avoiding full file loading.

Generating a list of prime numbers

function getPrimeNumbers($max) {
  $primes = [];

  for ($i = 2; $i <= $max; $i++) {
    if (isPrime($i)) {
      yield $i;
    }
  }

  return $primes;
}

foreach (getPrimeNumbers(100) as $prime) {
  echo $prime;
}

This generates all prime numbers up to the given maximum without storing the full list.

Lazy‑loading algorithm for a web application

function getItem($id) {
  $item = $this->database->getItem($id);

  if ($item) {
    yield $item;
  }
}

$app->get('/items/{id}', function ($id) {
  // fetch item
  $item = yield getItem($id);

  // render item
  return view('item', ['item' => $item]);
});

The item is loaded from the database only when needed, rather than loading everything up front.

Streaming video frames

function getVideoFrames($videoPath) {
  $file = fopen($videoPath, 'r');

  while (!feof($file)) {
    $frame = fread($file, 1024);
    yield $frame;
  }

  fclose($file);
}

$videoPlayer->play();

foreach (getVideoFrames('my_video.mp4') as $frame) {
  // display video frame
}

This streams video frames one chunk at a time, avoiding loading the entire video into memory.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPYield
php Courses
Written by

php Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.