Check whether a number is a Fibonacci number in PHP

Creating an algorithm to find all of fibonacci numbers between 0 and $x is a simple exercise in recursion, but how do we find out whether a given number is a fibonacci number?

The wikipedia entry gives us the algorithm, but how can we implement it in PHP? Below is a simple, fast code snippet that takes a number as input and returns true if the number is a fibonacci number, and false otherwise:

function isFibonacci($number) {
    $test_1 = sqrt(5 * pow($number, 2) + 4);
    $test_2 = sqrt(5 * pow($number, 2) - 4);

    return ctype_digit((string)$test_1) || ctype_digit((string)$test_2);

isFibonacci(25);   //false
isFibonacci(1597); //true

If this helped you, leave a message in the comments below! See you all next time!

Leave a Reply

Your email address will not be published. Required fields are marked *