Fibonacci code example in Python and PHP

These codes are only for fun and to show the usage of generators in PHP and Python languages.

Fibonacci in PHP

< ?php

$limit = 20;

function fib($limit) {
  $a = 0;
  $b = 1;

  while ($a < $limit) {
    yield $a; 
    $a = $b + $a;  // 1 1 2 3 5...
    $b = $a - $b;  // 0 1 1 2 3...
  }
}

foreach (fib($limit) as $num) {
  print $num."\n";
}

Fibonacci in Python

def fib(limit):
    a, b = 0, 1
    while a < limit:
        yield a
        a, b = b, a+b

for x in fib(10):
    print(x, end='\n')

Try to refactor the code to achieve the same output only this time yield on variable b instead of variable a. If you have question and comments, please leave them below.

Leave a Reply

Your email address will not be published. Required fields are marked *