Share
Preview
A generator is defined like a normal function, but instead of returning a value, it uses the yield keyword to return multiple values.
 ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌ ‌

ALEX WEB DEVELOP
Alex

The yield Keyword:
How to Return Multiple Times

XLS


Hey,
I'm Alex, from Alex Web Develop. I hope to find you well today.

With PHP you can create special functions called generators.
A generator is defined like a normal function, but instead of returning a value, it uses the yield keyword to return multiple values.

The yield keyword returns the value but, instead of exiting the function like return, it simply pauses the execution of the function.
The function can then be resumed from where it left off the next time it is called.

Here's an example of a simple generator function that yields the numbers from 0 to 9:

function simpleGenerator() {
  for ($i = 0; $i < 10; $i++) {
    yield $i;
  }
}


You can use generators in a few different ways.
For example, you can iterate over the values yielded by the generator using a foreach loop:

foreach (simpleGenerator() as $value) {
  echo $value;
}


This example will output the numbers from 0 to 9.

You can also get the current iterator's value with the current() method.
To make the iterator move on to the next value you can use the next() method.
For example:

$generator = simpleGenerator();
echo $generator->current(); // Outputs 0
$generator->next();
echo $generator->current(); // Outputs 1



Generators can also receive data through the send() method. The value passed to send() is returned by the yield command inside the function.
The generator can use this value in the next iteration.

For example, you can write a generator that increments a numeric counter by the value given with send():

function incrementGenerator() {
  $i = 0;
  while ($i < 1000) {
    $increment = yield $i;
    $i += $increment;
  }
}

$increment = incrementGenerator();
echo $increment->current();
$increment->send(5);
echo $increment->current();
$increment->send(15);
echo $increment->current();


The above example outputs the numbers: 0, 5, 20.


To sum up:
Generators are easy-to-implement, readable and memory-efficient iterators. They combine the advantages of other constructs minimizing their drawbacks:
  • They are almost as easy to implement as arrays, but the ability to yield one value at a time limits their memory footprint (a large array can eat a lot of memory).
  • They can be used as Iterators, but without the Iterators' complexity.
  • They are intuitive and readable as a for/foreach loop, but the code logic is neatly encapsulated into a function.



Links:

the cool bit

THE COOL BIT


Generator functions can also return values with the return keyword.
return will exit the function, as with standard functions.
To get the generator's return value you need to use the getReturn() method.

For example, the following generator yields values from 0 to 10 with increments of $inc. When the value goes over 10, it returns the exceeding offset from 10:

function incrementBy(int $inc) {
  $i = 0;
  $inc = max($inc, 1);
  while ($i <= 10) {
    yield $i;
    $i += $inc;
  }
  return $i - 10;
}

$increment = incrementBy(3);
foreach ($increment as $value) {
  echo $value . '<br>';
}

echo 'Exceeding: ' . $increment->getReturn();


The output is:

0
3
6
9
Exceeding: 2

tip of the week

TIP OF THE WEEK


Since PHP 8 you can use the str_contains() function to check if a string is contained in another string.
Before this function was available, you had to use str_pos() with strict comparison which was a less elegant solution.

Note that, unlike most PHP functions, the first argument is the string where to search in and the second argument is the string to search for.
For example:

$string1 = 'abc def ghi jkl';
$string2 = 'jkl';

if (str_contains($string1, $string2)) {
  echo 'The string "' . $string2 . '" is contained in "' . $string1 . '"';
}

// Output:
// The string "jkl" is contained in "abc def ghi jkl"
the challenge

WEEKLY CHALLENGE


Implement the Fibonacci sequence with a generator function (a classic excercise).
The $iterations argument sets how many numbers of the series should be yielded.
The advantage of using a generator is that you can generate a lot of values without using a lot of memory.


Let me know if you can solve it or if you need a hint.

function fibonacci($iterations) {
  //...
}

foreach (fibonacci(10) as $number) {
  echo $number . ' ';
}

// Output: 0 1 1 2 3 5 8 13 21 34
next steps

NEXT STEPS


Want to take your PHP skills to the next level?
Take a look at my professional PHP courses:


If you have any questions just reply to this email. I'm happy to help.


Before you go:
  • If you enjoyed this email, click here to share it with your friends.
  • Add my address (alex@alexwebdevelop.com) to your Contacts to make sure my next emails will reach you.
  • Send me a reply and let me know what you think. I read all the emails.

All the best,
Alex



Thanks to Freepik for the images used in this email.



You are receiving this newsletter because you subscribed to Alex Web Develop.

If you unsubscribe, you will not get any more emails from me.

Alessandro Castellano, P.IVA (VAT ID): 07012140484, via Luigi Morandi 32, 50141 Firenze FI, Italy

Email Marketing by ActiveCampaign