take an input x from the user and output x number of fibonacci numbers in php

main.php
<?php
// get input from user
$x = (int) readline("Enter the number of Fibonacci numbers you want to generate: ");

// initialize arrays with first two Fibonacci numbers
$fib_arr = array(0, 1);

// generate x number of Fibonacci numbers
for ($i=2; $i<$x; ++$i) {
    $fib_arr[$i] = $fib_arr[$i-1] + $fib_arr[$i-2];
}

// output the fibonacci numbers
echo implode(', ', $fib_arr);
?>
382 chars
16 lines

In the above program, we take input x from the user using readline() function. We convert the input to integer using type casting (int) to make sure we get a proper value. Then, we initialize an array with first two Fibonacci numbers (0 and 1). Finally, we use a for loop to generate x number of Fibonacci numbers and store them in the array. At last, we output the Fibonacci numbers using implode() function.

gistlibby LogSnag