Create fabonicci series program is a basic question in PHP for beginners if you go to a PHP Interview. So here is a PHP code that generates the Fibonacci series up to a specified number of terms:
<?php
// Function to generate the Fibonacci series
function fibonacci($n) {
// Initialize the first two terms of the series
$a = 0;
$b = 1;
// Generate the series up to the specified number of terms
for ($i = 0; $i < $n; $i++) {
// Print the current term
echo $a . " ";
// Calculate the next term in the series
$c = $a + $b;
// Update the values of the first two terms
$a = $b;
$b = $c;
}
}
// Generate the Fibonacci series up to 10 terms
fibonacci(10);
?>
This code defines a function called fibonacci()
that takes an integer as an argument and generates the Fibonacci series up to that number of terms. The function initializes the first two terms of the series to 0 and 1, respectively, and then uses a loop to generate the remaining terms. The loop calculates the next term in the series by adding the previous two terms and then updates the values of the first two terms for the next iteration.
To use this code, simply call the fibonacci()
function and pass it the desired number of terms as an argument. For example, to generate the Fibonacci series up to 10 terms, you would call fibonacci(10)
. This will output the series to the screen, with each term separated by a space.
If you want to create this program without a function then here is the code for it.
<?php
// Initialize the first two terms of the series
$a = 0;
$b = 1;
// Get the number of terms from the user
$n = 10;
// Generate the series up to the specified number of terms
for ($i = 0; $i < $n; $i++) {
// Print the current term
echo $a . " ";
// Calculate the next term in the series
$c = $a + $b;
// Update the values of the first two terms
$a = $b;
$b = $c;
}
?>
This code initializes the first two terms of the series to 0 and 1, respectively, and then uses a loop to generate the remaining terms. The loop calculates the next term in the series by adding the previous two terms and then updates the values of the first two terms for the next iteration.
To generate the Fibonacci series up to a different number of terms, simply change the value of the $n
variable. For example, to generate the series up to 15 terms, you would set $n = 15
. This will output the series to the screen, with each term separated by a space.
I hope, it will help.