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.
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:
<code>function getNumbers() {
$numbers = [1, 2, 3, 4, 5];
foreach ($numbers as $number) {
yield $number;
}
}
</code>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:
<code>foreach (getNumbers() as $number) {
echo $number;
}
</code>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
<code>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'];
}
</code>This code iterates all products and prints each name without loading the entire result set into memory.
Processing a large CSV file
<code>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
}
</code>The CSV is processed line‑by‑line, avoiding full file loading.
Generating a list of prime numbers
<code>function getPrimeNumbers($max) {
$primes = [];
for ($i = 2; $i <= $max; $i++) {
if (isPrime($i)) {
yield $i;
}
}
return $primes;
}
foreach (getPrimeNumbers(100) as $prime) {
echo $prime;
}
</code>This generates all prime numbers up to the given maximum without storing the full list.
Lazy‑loading algorithm for a web application
<code>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]);
});
</code>The item is loaded from the database only when needed, rather than loading everything up front.
Streaming video frames
<code>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
}
</code>This streams video frames one chunk at a time, avoiding loading the entire video into memory.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.