0
0
PHPprogramming~3 mins

Why Yield keyword behavior in PHP? - Purpose & Use Cases

Choose your learning style9 modes available
The Big Idea

What if you could handle huge data without slowing down or crashing your program?

The Scenario

Imagine you have a huge list of data, like thousands of user records, and you want to process them one by one.

If you try to load all data into memory at once, your program might slow down or crash.

The Problem

Loading everything at once uses a lot of memory and can make your program freeze.

Also, writing loops that store all results before using them can be slow and waste resources.

The Solution

The yield keyword lets you produce one item at a time, like handing out cards one by one instead of the whole deck.

This way, your program uses less memory and can start working immediately without waiting for everything.

Before vs After
Before
$results = [];
foreach ($data as $item) {
    $results[] = process($item);
}
return $results;
After
function processData($data) {
    foreach ($data as $item) {
        yield process($item);
    }
}
What It Enables

You can handle large data smoothly and efficiently, making your programs faster and more memory-friendly.

Real Life Example

Think of reading a huge log file line by line instead of loading the entire file into memory at once.

Key Takeaways

Yield helps produce data one piece at a time.

It saves memory and speeds up processing.

Great for working with large or infinite data sets.