PHP | Fibonacci Series
The Fibonacci series is a series of elements where, the previous two elements are added to get the next element, starting with 0 and 1. In this article, we will learn about how to generate a Fibonacci series in PHP using iterative and recursive way. Given a number n, we need to find the Fibonacci series up to the nth term.
Examples:
Input : 10 Output : 0 1 1 2 3 5 8 13 21 34 Input : 15 Output : 0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
Method 1: Using Recursive way
Recursion is a way where we repeatedly call the same function until a base condition is matched to end the recursion.
<?php // PHP code to get the Fibonacci series // Recursive function for fibonacci series. function Fibonacci($number){ // if and else if to generate first two numbers if ($number == 0) return 0; else if ($number == 1) return 1; // Recursive Call to get the upcoming numbers else return (Fibonacci($number-1) + Fibonacci($number-2)); } // Driver Code $number = 10; for ($counter = 0; $counter < $number; $counter++){ echo Fibonacci($counter),' '; } ?> |
Output:
0 1 1 2 3 5 8 13 21 34
Method 2: Using the iterative way
At first, we initialize the first and second number to 0 and 1. Following this, we print the first and second number. Then we send the flow to the iterative while loop where we get the next number by adding the previous two number and simultaneously we swap the first number with the second and the second with the third.
<?php // PHP code to get the Fibonacci series function Fibonacci($n){ $num1 = 0; $num2 = 1; $counter = 0; while ($counter < $n){ echo ' '.$num1; $num3 = $num2 + $num1; $num1 = $num2; $num2 = $num3; $counter = $counter + 1; } } // Driver Code $n = 10; Fibonacci($n); ?> |
Output:
0 1 1 2 3 5 8 13 21 34
Recommended Posts:
- PHP program to print an arithmetic progression series using inbuilt functions
- Create a Hoverable Side Navigation with HTML, CSS and JavaScript
- JavaScript Interview Questions and Answers | Set 3
- When to use Vanilla JavaScript vs jQuery ?
- How to detect the user browser ( Safari, Chrome, IE, Firefox and Opera ) using JavaScript ?
- How to animate scrollTop using jQuery ?
- How to select text nodes using jQuery ?
- Why require_once() function is so bad to use in PHP ?
- How to convert arguments object into an array in JavaScript ?
- HTML | DOM FocusEvent
- PHP | Imagick setCompression() Function
- PHP | Imagick getImageAlphaChannel() Function
- HTML5 | MathML <munderover> Tag
- PHP | image_type_to_extension() Function
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



