In this Example on how to display the Fibonacci sequence of first n numbers (entered by the user) using recursive function. Also in different example, you learn to generate the Fibonacci sequence up to a certain number in PHP.
Code 1: Fibonacci Series Program in PHP
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 |
<?php // PHP code to get the Fibonacci series Recursive function for fibonacci series. function Fibonacci($number){ if ($number == 0) return 0; else if ($number == 1) return 1; else return (Fibonacci($number-1) + Fibonacci($number-2)); } ?> <!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 Numbers"> </form> <?php if(isset($_POST["print"])) { $number = $_POST["number"]; for ($counter = 0; $counter < $number; $counter++){ echo '<strong>'.Fibonacci($counter).'</strong> '; } } ?> </body> </html> |
Output: PHP Fibonacci Sequence
Code 2: 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: