Iterative Method
First, we define a function that takes an integer $n as a parameter. Inside the function, we initialize two variables, $f1 and $f2 with 0 and 1 respectively. These represent the first two numbers in the Fibonacci sequence.
Then we use a for loop to calculate the Fibonacci sequence up to the Nth number. The loop starts from 2 because the first two numbers are already initialized. In each iteration, we calculate the next Fibonacci number and update the values of $f1 and $f2 accordingly. The function returns the value of the Nth Fibonacci number, which is stored in the variable $f2.
PHP
<?php function fibNumber( $n ) { $f1 = 0; $f2 = 1; for ( $i = 2; $i <= $n ; $i ++) { $next = $f1 + $f2 ; $f1 = $f2 ; $f2 = $next ; } return $f2 ; } // Driver Code $n = 10; echo "The {$n}th Fibonacci number is: " . fibNumber( $n ); ?> |
The 10th Fibonacci number is: 55
PHP Program for Nth Fibonacci Number
The Fibonacci sequence is a series of numbers where each number is the sum of the two preceding ones, usually starting with 0 and 1. In this article, we will write a PHP program to find the Nth Fibonacci number.
Table of Content
- Iterative Method
- Recursive Method
Contact Us