Caroline M - 4 years ago 107
PHP Question

# Difficulties with is_int function in PHP

I'm writing a code to solve a problem.one of my functions is not working properly.

``````function check_factor(\$sqr,\$num)
{
for(\$i = \$sqr ; true ; \$i++)
{
\$n = pow(\$sqr,2) - \$num;
\$s = sqrt(\$n);
if(is_int(\$s))
{
return \$i;
}
}

}
``````

I know that \$s is a "double" , but even when I limit my loop counter to 2,I'll get an endless loop.
What am I missing here? why the function doesnt simply return null? and why I get Infinite loop even when there are 2 iterations?

true is making it an infinite loop

you will always get an infinit loop because sqrt() returns float means

``\$s = sqrt(\$n);``

\$s is a float now

and your test is testing if \$s is an integer so it will be an infinit loop even after \$i=2 the loop will always stuck and the \$i=2 in every loop but if you change the code to this

``````<?php
function check_factor(\$sqr,\$num)
{
echo "<br>";
for(\$i = 1 ; \$i < 3  ; \$i++)
{
echo " in the loop \$i<br>";
\$n = pow(\$sqr,2) - \$num;
echo "\$n<br>";
\$s = sqrt(\$n);
echo "\$s<br>";
if(is_int(\$s))
{
echo "in the if <br>";
return \$i;
}
}
return 0;
}
\$val=0;
\$val = check_factor(5,2);
echo "<br>\$val<br>";
?>``````

the out put should be like this

``````in the loop 1
23
4.7958315233127
in the loop 2
23
4.7958315233127

0``````

and that's it. i hope i helped.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download