Skip to content
Advertisement

php simple rand() look up taking long / crashing browser?

I’m running this code:

$n1 = rand(1,20);
$n2 = rand(1,20);
echo '<p>Looking for ' . $z1;
echo '<p>looking....<br><br>';
for ($i = 1; $n1 != $n2; $i ++) {
  $n2 = rand(1,10);
}

echo '<p>I tried ' . $i . ' times.</p>';

First loads of the page are usually super fast. Then suddenly:

Fatal error: Maximum execution time of 120 seconds exceeded

It’s either working super fast or crashing. Can someone help me understand why this is?

Thank You

Advertisement

Answer

You have committed a “logic” mistake.

If $n1 = rand(1,20); sets $n1 to any number from 11 to 20, then the condition in your loop will never be satisfied and result in an “infinite loop”.

In other words, roughly half of your code executions will result in infinite loops and half will not.

$n2 = rand(1,10); needs to be $n2 = rand(1,20); so that all possible $n1 values can be matched.

Might I recommend:

$n = rand(1, 20);
echo "<p>Looking for $n</p>";
$i = 0;
do {
    ++$i;
} while($n != rand(1, 20));

echo "<p>Tries: $i </p>";

Ultimately, whenever a random generator is used to determine a loop’s break condition, it can be sensible to set an arbitrary “maximum iterations” value. Once that is reached, let your script exit the loop.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement