$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.
}
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
functiongenerateFibonacci($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: 1generateFibonacci(1); // Output: 0
?>