Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assignment in do-while/while doesn't work as expected

I want to assign a random value between 48 and 122 to $num except for the value 79.

So to slove this I tried a do-while and a while loop to solve the problem. I tested it, but it doesn't work as expected and it ends in an endless loop.

while($num != 79){
    $num =  rand(48, 122);
};

or:

do {
    $num = rand(48, 122);
} while ($num != 79);

So why doesn't this work as I want it to? Can anyone tell me where my mistake is?

$num shout be a number between 48 and 122 but NOT 79.

like image 728
hamburger Avatar asked May 23 '26 19:05

hamburger


1 Answers

In both cases the logic is wrong, you're repeating the loop while your number is not 79

You should repeat the loop if the number is 79:

$num = 79;// assign value to avoid Notice error 
while($num == 79){ 
    $num =  rand(48, 122);
};

or:

do {
    $num = rand(48, 122);
} while ($num == 79);
like image 75
the-noob Avatar answered May 25 '26 07:05

the-noob