In this example, I am using a for loop and I am getting the limiting number from user.
Code 1: Print Fibonacci Series With Using Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>Code 4 Example - PHP Examples</title> </head> <body> <form action="" method="post"> Number:<input type="text" name="number" value="<?=$_POST['number']??''?>"><br> <input type="submit" name="print" value="Print Fibonacci Series"> </form> <?php if(isset($_POST["print"])) { $limit=$_POST["number"]; $x = 0; $y = 1; $fib = [$x,$y]; for($i=0;$i<=$limit-2;$i++) { $z = $x + $y; $fib[]=$z; $x=$y; $y=$z; } echo "<pre>"; //print series print_r($fib); echo "</pre>"; } ?> </body> </html> |
Output:
Code 2: Print Fibonacci Series With Recursive
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | <?php function fibonacci($n,$first = 0,$second = 1) { $fib = [$first,$second]; for($i=1;$i<$n;$i++) { $fib[] = $fib[$i]+$fib[$i-1]; } return $fib; } ?> <!doctype html> <html> <head> <meta charset="utf-8"> <title>Code 4 Example - PHP Examples</title> </head> <body> <form action="" method="post"> Number:<input type="text" name="number" value="<?=$_POST['number']??''?>"><br> <input type="submit" name="print" value="Print Fibonacci Series"> </form> <?php if(isset($_POST["print"])) { $limit=$_POST["number"]; $fibArray=fibonacci($limit); //print series echo "<pre>"; print_r($fibArray); echo "</pre>"; } ?> </body> </html> |
Code 2: Print Fibonacci Series Without Using Array
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | <!doctype html> <html> <head> <meta charset="utf-8"> <title>Code 4 Example - PHP Examples</title> </head> <body> <form action="" method="post"> Number:<input type="text" name="number" value="<?=$_POST['number']??''?>"><br> <input type="submit" name="print" value="Print Fibonacci Series"> </form> <?php if(isset($_POST["print"])) { $limit=$_POST["number"]; $x = 0; $y = 1; for($i=0;$i<=$limit-1;$i++) { $z = $x + $y; echo "<strong>$z</strong> "; $x=$y; $y=$z; } } ?> </body> </html> |
Output:
your expression on using Fibonacci sequence on array php is a light pad to me work. it is indeed helpful and educative.