How to generate the Fibonacci sequence with PHP

Josh Sherman
1 min read
Software Development PHP

The Fibonacci sequence is a sequence of numbers that are derived from the previous numbers in the sequence. The sequence starts at zero and each subsequent number is sum of the previous two numbers in the sequence. There are a number of ways to accomplish this and the most common caveat is to store every single number in the sequence instead of just the previous two which allow you to get to the next number. Here’s one way to generate the Fibonacci sequence for the first 100 values in PHP:

$max  = 354224848179261915075; // Adjust me for more values
$i    = 0;
$next = 1;

while ($i <= $max) {
    echo $i . "\n";

    $tmp  = $i;
    $i   += $next;
    $next = $tmp;
}

If you’re interested in doing this in JavaScript, feel free to check out my buddy Justin’s blog post about it. Got a better way to do it? Comment below, I’d love to see your solutions!

Join the Conversation

Good stuff? Want more?

Weekly emails about technology, development, and sometimes sauerkraut.

100% Fresh, Grade A Content, Never Spam.

About Josh

Husband. Father. Pug dad. Musician. Founder of Holiday API, Head of Engineering and Emoji Specialist at Mailshake, and author of the best damn Lorem Ipsum Library for PHP.

Currently Reading

Parasie Eve

Previous Reads

Buy Me a Coffee Become a Sponsor

Related Articles