php - while-loop with an empty body and an assignment in the condition
Get the solution ↓↓↓I recently encountered the following construct on an abandoned PHP code project:
while(($my_var = mt_rand(3, 6))%2 != 0);
(Note the empty body of the loop). This ensures that $my_var is assigned either the number 4 or the number 6.
Is there any (measurable, objective) advantage in using the above construction, over something like
$my_var = mt_rand(2, 3) * 2;
(I am particularly wondering why the author chose to include 3 in the randomization range if the result has to be even anyway.)
Answer
Solution:
while(($my_var = mt_rand(3, 6))%2 != 0);
This ensures that $my_var is assigned either the number 4 or the number 6.
As @Oli mentioned in comments, this is very convoluted and hard to read.
And it also has the disadvantage, that you can not really predict how many times it will iterate.
It could (theoretically) “throw the dice” and come up with 5 for the first ten, hundred or thousand iterations ... or even never end. (The implementation ofmt_rand
is likely good enough for that not to happen, but still.)
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: an exception occurred in the driver: could not find driver
Didn't find the answer?
Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.
Similar questions
Find the answer in similar questions on our website.
Write quick answer
Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.