Why doesn't this code works properly?!
We have an infinite loop here! I want finish the loop when we have 3 top or 3 bottom in a row(it's top and bottom of a coin actually).
<?php
$top = 0;
$bottom = 0;
$flipCount = 0;
while (($top < 3) || ($bottom < 3)) {
$flip = rand(0,1);
$flipCount ++;
if ($flip){
$top++;
$bottom = 0;
echo "<div>top</div>";
}
else {
$bottom++;
$top = 0;
echo "<div>bottom</div>";
}
}
echo "$flipCount flips!";
Everytime you have a flip (not matter if it's previously a "top" or "bottom"), then you are resetting the other one. This is wrong. You will only need to reset it if the previous flip is different than the current flip and the total number of flips is less than 3. The condition in your loop is also wrong, it should be:
while (($top != 3) && ($bottom != 3))
<?php
$top = 0;
$bottom = 0;
$flipCount = 0;
while (($top < 3) || ($bottom < 3)) {
$flip = rand(0,1);
$flipCount++;
if ($flip){
$top++;
$bottom = 0;
echo "<div>top</div>";
}
else {
++$bottom;
$top = 0;
echo "<div>bottom</div>";
}
if($top > 2 || $bottom > 2){
break;
}
}
echo "$flipCount flips!";
> Blockquote