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:
I defined some variables, too:
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);.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
<?php function fibonacci($antal,$reverse) { $tal = 0; $next = 1; for ($i = 0; $i <= $antal; $i++) { $outputs[$i] = $tal; $Gltal = $tal; $tal = $tal+$next; $next = $Gltal; } if ($reverse) {$outputs = array_reverse($outputs);} foreach ($outputs as $output) {echo $output." ";} } ?> Tha Fibonacci sequence by Troels Madsen! <?php fibonacci(20,0); ?> Tha REVERSE Fibonacci sequence, again by Troels Madsen! <?php fibonacci(20,1); ?> |
1 2 3 4 5 |
Tha Fibonacci sequence by Troels Madsen! 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 2584 4181 6765 Tha REVERSE Fibonacci sequence, again by Troels Madsen! 6765 4181 2584 1597 987 610 377 233 144 89 55 34 21 13 8 5 3 2 1 1 0 |