PHP Program for Nth Fibonacci Number
Last Updated :
27 Dec, 2023
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.
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 ;
}
$n = 10;
echo "The {$n}th Fibonacci number is: "
. fibNumber( $n );
?>
|
Output
The 10th Fibonacci number is: 55
Recursive Method
A recursive solution involves defining a function that calls itself to solve subproblems. First, we call a function with number $n i.e. fibNumber($n), and then check if number is less then or equal to 1, then it returns number, otherwise it returns fibNumber($n – 1) + fibNumber($n – 2).
PHP
<?php
function fibNumber( $n ) {
if ( $n <= 1) {
return $n ;
}
return fibNumber( $n - 1) + fibNumber( $n - 2);
}
$n = 10;
echo "The {$n}th Fibonacci number is: "
. fibNumber( $n );
?>
|
Output
The 10th Fibonacci number is: 55
Share your thoughts in the comments
Please Login to comment...