How to generate Fibonacci numbers
Short answer
Each number is the sum of the two before it:
<?php
$numbers = [];
[$a, $b] = [0, 1];
for ($i = 0; $i < 10; $i++) {
$numbers[] = $a;
[$a, $b] = [$b, $a + $b];
}
echo implode(', ', $numbers);Output:
0, 1, 1, 2, 3, 5, 8, 13, 21, 34A generator
A generator yields numbers one at a time and does not store the whole list:
<?php
function fibonacci(): Generator
{
[$a, $b] = [0, 1];
while (true) {
yield $a;
[$a, $b] = [$b, $a + $b];
}
}
foreach (fibonacci() as $number) {
if ($number > 100) {
break;
}
echo $number, ' ';
}Output:
0 1 1 2 3 5 8 13 21 34 55 89Functions used in this recipe
- Generator — The object returned by a function containing `yield`.
- iterator_to_array — Turns an iterator or a generator into an array.
- array_sum — Returns the sum of the values in an array.