How to Create a Sequence in PHP

With PHP you can implement a sequence with a generator function.

A generator is a special type of function that returns multiple values.

It works like an iterator, where each iteration gives you the next value of the sequence.

Let’s take a simple example:

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

In this example, the simpleGenerator() function works as a sequence of the numbers from 0 to 9.

The function contains a for loop, with the $i variable going from 0 to 9.

For every value of $i, the function uses the yield keyword to return the value of $i.

By using yield instead of return, the function does not exit after giving the value, but it waits for the caller to ask for the next value.

Here’s how you can use it:

foreach (simpleGenerator() as $value) {
  echo $value;
Output: 0 1 2 3 4 5 6 7 8 9

Generators also provide explicit methods to navigate through their values.

When you create a generator function (that is, any function that implements the yield keyword), that function automatically implements the generator methods.

For example, you can achieve the same result of the previous example by using the current() and next() methods:

$generator = simpleGenerator();
$value = $generator->current();
while (!is_null($value)) {
   echo $value;
   $value = $generator->current();

You can also create infinite sequences with generators.

For example, you can implement a function that takes an integer as its argument and creates an infinite sequence of all the multiples of that number.

Then, you can iterate through the sequence up to a certain value, or for a specific number of times.

Like this:

function multiplesOfN(int $n) {
   $value = $n;
   while (true) {
      yield $value;
      $value += $n;
$multiples = multiplesOfN(5);
$value = $multiples->current();
while ($value <= 100) {
   echo $value . " ";
   $value = $multiples->current();
5 10 15 20 25 30 35 40 45 50 
55 60 65 70 75 80 85 90 95 100

That’s it.

If you have any questions just leave a comment below.


Leave a Comment