amirali
amirali

Reputation: 1964

My PHP code runs with no errors but infinitely loads

I'm new to PHP, And I tried to write a program in which finds the nearest number of power 2 to a defined variable (here it's $input).

Amazingly it runs, Shows no errors, But loads infinitely! I tried php_codesniffer, But it didn't show any errors, So We can make sure it isn't a syntax error. I also tried restarting apache which didn't help. To make sure it's not from apache, I tried running my other codes which there were no problem in running them on apache server. Here is my code:

<?php

$no = 5443.985;

// this function gets a nomber $input and returns the nearest number to $input between $checkingNo_one & $checkongNo_two
function check_nearer($input, $checkingNo_one, $checkingNo_two)
{
    if (($input - $checkingNo_one) >= ($checkingNo_two - $input)) {
        return $checkingNo_two;
    } else {
        return $checkingNo_one;
    }
}

$twoPower = 1;
while ($twoPower < $no) {
    $twoPower **= 2;
}
$twoPower_alt = $twoPower ** 2; // to see if the number after our input isn't nearer to it

$returningNo = check_nearer($no, $twoPower, $twoPower_alt);
echo $returningNo;

what do you think?

Upvotes: 1

Views: 58

Answers (1)

undrown
undrown

Reputation: 32

Simply change $twoPower = 1; to $twoPower = 2;; because you are trying to multiply 1 to itself which will always be 1 and will never end:

while ($twoPower < $no) {
    $twoPower **= 2;
}

Upvotes: 1

Related Questions