flux flux - 6 months ago 7
PHP Question

Trying to use PHP 'do-while' loop to find a random number

I want to use PHP do while loop and find a random number.

Here is the code, it's not working...

<?php

$start = 10;
$end = 1;
$find = rand(0,9);

do {
if ($start == $find):
echo "Found!";
elseif ($start != $find):
echo $start;
$start = $start - $end;
endif;
} while ($start != $find);

?>

Answer

At the last iteration, when with $start = $start - $end; the $start variable becomes equal to $find, you immediately get out of the loop (because while ($start != $find); is false in that moment). That's mean that

if ($start == $find):
     echo "Found!";

will never occur. If you understand this, then you understand that out of the loop $start == $find is always verified. So you can move that piece of code at the bottom:

$start = 10;
$end = 1;
$find = rand(0,9); 

do { 
    if ($start != $find): // ALWAYS true, can be omitted
        echo $start; 
        $start = $start - $end;
    endif;
} while ($start != $find);

if ($start == $find): // ALWAYS true, can be omitted
    echo "Found!";
endif;
Comments