This php method is suppose to print the Fibonacci sequence up to a specified value using a for loop. I am unsure why it does not work?
<?php
function fib ($n) { // a function called fib, declaire variable n (the sequence number)
for ($n=0;$n<30;$n++) {
if ($n < 3) { return $n; } // if n is smaller than 3 return n (1 or 2)
else { return fib ($n - 1) + fib ($n - 2); }
/* if the number is 3 or above do 2 sums (n-1) and (n-2)
and then add the 2 sums together (n-1)+(n-2)
Example Fibonacci number 4
(4-1)+(4-2) = 5
3 + 2 = 5
*/
}
print $n;
?>
There is actually a way to calculate a Fibonacci number without iteration by using rounding:
http://en.wikipedia.org/wiki/Fibonacci_number#Computation_by_rounding
function getFib($n)
{
return round(pow((sqrt(5)+1)/2, $n) / sqrt(5));
}
Simple function of fibonacci
function fibonacci($n,$first = 0,$second = 1)
{
$fib = [$first,$second];
for($i=1;$i<$n;$i++)
{
$fib[] = $fib[$i]+$fib[$i-1];
}
return $fib;
}
echo "<pre>";
print_r(fibonacci(50));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With