The Magic Data Faucet: Understanding yield in PHP and Laravel

Adrian Generous
3 min readFeb 12, 2024

In the realm of programming, we often encounter challenges related to efficiently processing and managing large data sets. Whether dealing with huge files or scouring through database records, the key aspect is to optimize memory usage and processing time. Here, yield, a seemingly modest keyword in PHP, turns out to be a magic data faucet, controlling the flow of information in our applications without overwhelming them with a deluge of data.

How Does yield Work?

Imagine yield as a garden faucet that allows controlled water flow. In the PHP context, yield enables pausing and resuming function execution, passing data step by step, instead of returning it all at once. This makes it perfectly suited for processing large data sets, allowing for "lazy" loading of only the needed data chunks on demand.

Practical Applications of yield

Searching for Players in the English League

Let’s imagine we are dealing with a massive CSV file containing data about football players. This time, we want to find all players who play in the English league without having to load the entire file into memory:

function readPlayers($filePath) {
$file = fopen($filePath, 'r');
while (!feof($file)) {
$player = fgetcsv($file);
if ($player[3] == "English League") { // Assuming the league information is in the fourth column…

--

--

Adrian Generous

I navigate between coding & marketing, experienced as a CTO, project manager, & ad agency owner. I share Laravel & more on Medium, also a history enthusiast.