Fibonacci series of numbers in PHP

In Fibonacci series of numbers, each number is the sum of the two preceding ones.
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
Fn = F(n-1) + F(n-2)

Generating Fibonacci series in PHP where any number is sum of previous two numbers

Generating Fibonacci series using for loop

We will use for loop to generate the series.
$n1=1; // first number 
$n2=0; // second number
for($i=0;$i<=15;$i++){
echo " $n2,";
$temp=$n1+$n2; // temporary variable  
$n1=$n2;   // $n2 value shifted to $n1 
$n2=$temp; // temporary value ( sum ) is shifted. 	
}
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610,

Using recursive function

function fibo($n){
if($n<=1){
return $n;}
else{
	return (fibo($n-1)+fibo($n-2));
}	
}

for ($i=0;$i<15;$i++){
echo fibo($i).", ";
}
Output
0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377,
Introduction to PHP Factorial of a number Sum of Digits of a number
Armstrong number Strong number
Basic Codes Check the string or number is Palindrome or not in PHP
Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Post your comments , suggestion , error , requirements etc here





    PHP video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer