Jump to content

do-while not working as it should..


Go to solution Solved by Sepodati,

Recommended Posts

Hi, I'm new to php so I'm trying to code some random stuff..

<?php    
    $headCount = 0;
    $loopCount = 0;
    do {
        $flip = rand(0,1);
    if($flip = 0) {
        echo "<p>H</p>";
        $loopCount++;
        $headCount++;
    }
    else {
        echo "<p>T</p>";
        $loopCount++;
        $headCount = 0;
    }
    } while($headCount == 2 or $loopCount == 5); //should flip it til loopcount reach 5 or headcount reach 2
    
    if($loopCount <= 5 && $headCount == 2) {
        echo "<p>We rolled " . $headCount . " heads in a row in " . $loopCount . " flips.</p>";
    }
    else {
        echo "<p> " . $loopCount . " roll(s) was not enough to get two <b>H</b> in a row.</p>";
    }
    ?>

but all it does is in a screenshot .. thanks!yMc3moZ.png

Link to comment
https://forums.phpfreaks.com/topic/305596-do-while-not-working-as-it-should/
Share on other sites

  • Solution

Your logic is flawed. The loop will only continue if the conditions evaluate to true. $headcount is not equal to 2 and $loopcount is not equal to 5, so the condition fails and the loop exists after the first go.

 

What I think you want is the loop to continue while $headcount is less than 2 or $loopcount is less than 5.

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.