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,
Question

Write a PHP function, generateFibonacci(), that accepts an argument to represent a number (n) and displays the nth number in the Fibonacci series . The series is 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144… For example, invoking the function using the statement generateFibonacci(3)should display 1 as the output, as 5 is the 6th number in the series
<?php
function generateFibonacci($n) {
    if ($n < 1) {
        echo "Invalid input. Please enter a positive integer.";
        return;
    }

    // Handle the first two numbers
    if ($n == 1) {
        echo "0";
        return;
    } elseif ($n == 2) {
        echo "1";
        return;
    }

    // Generate Fibonacci for n >= 3
    $a = 0;
    $b = 1;
    for ($i = 3; $i <= $n; $i++) {
        $temp = $a + $b;
        $a = $b;
        $b = $temp;
    }

    echo "" . $b . "";
}

// Example usage
//generateFibonacci(7); // Output: 8
//generateFibonacci(3); // Output: 1
generateFibonacci(1); // Output: 0
?>
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











    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