How to generate the Fibonacci sequence with 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!

Josh Sherman - The Man, The Myth, The Avatar

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.


If you found this article helpful, please consider buying me a coffee.