Been trying this for a while and even searched the net but didn't get what I am doing wrong, I got the function but it's just that it won't print the two first digits that is supposed to be 0 and 1 followed by what's get printed by my code.

<?php
//Create a function
function fibonacci($nr){
    //Make an array to hold the numbers
    $prev = array(0, 1);
    //Make the loop
    for ($i = 0; $i < $nr; $i++){
        //Number is the sum of the previous two
        $num = $prev[0]+ $prev[1];
        //Echo out the number
        echo $num . '<br>';
        //The sum of the two numbers is put in the second array
        $prev[0] = $prev[1];
        //The second array holds the new value
        $prev[1] = $num;
    }
}
//Enter how many numbers you would like to generate
fibonacci(15);
?>

The two starting numbers is there in the array (0, 1), what am I missing?

Recommended Answers

All 3 Replies

Your first step, outside the loop, should be to print the the first two numbers that you are seeding the array with
echo $prev[0];
echo $prev[1];
then continue up to your target value in the loop.
but loop like htis
for ($i = 2; $i < $nr; $i++)
or you will go two steps past the limit the users asked for.
Simples.

how about printing those first two numbers before entering the loop since they're static output for all fibonacci cases

Yeah I just thought about this, I got 0 and 1, 0+1=1 and so on so obviously it won't print the first 0 then 1.

Your right, I should just echo them out, thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.