PHP

The Fibonacci mystery!

Open the code and compare it to my explain here: http://codepad.org/1PX8zItx

To challenge myself in the exercise from lecture #5, I chose to work with The Fibonacci sequence in PHP.

I make a fibonacci(); function with a for-loop. In the functions I have some arguments set for the function:

  • $antal: the number times the loop must runs (Is customizable in the function argument)
  • $reverse: Can be called true to let the loop be in the reversed form (Is customizable in the function argument. Default = 0).

I defined some variables, too:

  • $tal: The current number (0)
  • $next: The next number, which must be added in the next queue (1)

In the for loop I use the variable $i, which is the number loop, the loops is running now, and it must be added by 1 for each times the loop runs. the loop stop when $i is more than $antal.

The for loop creates a array variable $outputs, which stores all values in a array. Later on I can print the array by using a foreach loop, and print the outputs altogether with a space. But prior to that, I wanted to checked if the $reverse variable is true, and if it’s true, it would reverse the $outputs array using a array_reverse(); function prebuilt with php.

Last, I use the function by write two lines of code, one for the default sequence with 20 numbers: fibonacci(20,0); and the reversed form as fibonacci(20,1);.

The code:

 The output: