UPDATE: ADDED THREE NEW WAYS THAT YOU CAN DO THIS IN PHP.
IF YOU WANT TO SEE IT IN ACTION, CLICK HERE
Well I finally got it to work, and I felt that I should share this with the Open Source world.
Here it is, the Fibonacci Sequence coded in PHP.
If you are looking for some webhosting to practice with PHP, TylerPerroux.com recommends Bluehost.com
WARNING: THIS CAN CAUSE YOUR SERVER/COMPUTER TO CRASH IF USED INDIRECTLY. HOPEFULLY PHP WOULD CATCH THIS, AS THIS SCRIPT CAN CAUSE A NEAR ENDLESS LOOP. THERE IS NO WARRANTLY, EITHER IMPLIED OR EXPRESSED THAT THIS SCRIPT WORKS. ANY HARM THAT MAY HAPPEN BECAUSE OF THE IMPROPER/PROPER USE OF THIS SCRIPT IS IN NO WAY MY FAULT. FULL DISCLAIMER.
<?php
/**
* Example Fibonacci implementation to (n) steps (without recursion)
* @return array
@var $req - Array of Fibonacci numbers
*/
function fibonacci1( $steps = 10 )
{
list($current,$next,$curnum,$seq ) = array( 0, 1, 1, array() );
do
{
$curnum++;
$seq[] = $current;
$add = $current + $next;
$current = $next;
$next = $add;
} while ( $curnum <= $steps );
return $seq;
}
// Example of first 15 Fibonacci numbers
echo "1) ";
print_r(fibonacci1(15));
echo "<br/>";
echo "2) ";
// This changes it from a multi-dimensional arry to a normal one.
foreach(fibonacci1(15) as $asdd => $asddd){
echo $asddd . " ";
}
function fibonacci2($n)
{
if($n == 0)
return 0;
elseif ($n == 1)
return 1;
else
return fibonacci2($n - 1) + fibonacci2($n - 2);
}
echo "<br>";
echo "3) ";
for($i = 0; $i < 15; $i++)
{
echo fibonacci2($i) . " ";
}
?>
<?php
/**
* The fibonacci function should look familiar.
*/
echo "<br>";
function fibonacci3($n){
$a = 0;
$b = 1;
for ($i = 0; $i < $n; $i++){
printf("%d\n",$a);
$sum = $a+$b;
$a = $b;
$b = $sum;
}
}echo "4) ";
fibonacci3(15);
echo "<br>";
show_source(__FILE__);
?>
Alright this explains everything.
1) This is a function that outputs a multi-dimensional array, without using recursion. $current_Number => $fibonacci_Num
2) Uses the same thing as 1, but cleans it up to only output the $fibonacci_Num
3) This uses recursion, and the base of it is a use of the explicit formula given.
4) This is just a simple for loop to output the numbers. Easy.
–Tyler Perroux
{ 0 comments }

