0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377
Fn = F(n-1) + F(n-2)$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,
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<?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 PHPFactorial of a number Sum of Digits of a number
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.