Jiang Lan
Jiang Lan

Reputation: 171

How to repeat the do while until I get the number I want in php?

I'm doing a "do while" php lesson in "codecademy".
The objective is to throw the dice until we get 6.
Here is the code I wrote, it runs but not exactly what I want.

<?php
    $nombreJet = 0;
    do {
      $jet = rand(1,6);
      $nombreJet++;
      if($jet){
        echo "<div>$jet</div>";
      };   
    } while ($jet == 6);
?>

No matter what I get and how many times, it should always end by 6.
But now I get 3 or 5 2 or 1 4 1 etc without 6 at the end.
How to correct it? Thanks!

Upvotes: 0

Views: 75

Answers (2)

Sumit Kumar
Sumit Kumar

Reputation: 580

For ending your result with 6,You need to change your while condition.

 <?php
$nombreJet = 0;
    do {
      $jet = rand(1,6);
      $nombreJet++;
      if($jet){
        echo "<div>$jet</div>";
      };   
    } while ($jet != 6);
?>

Upvotes: 2

jackomelly
jackomelly

Reputation: 543

If you want to execute the cycle until you get 6, invert the condition at end.

$nombreJet = 0;
do {
  $jet = rand(1,6);
  $nombreJet++;
  if($jet){
    echo "<div>$jet</div>";
  };
} while ($jet != 6);

Upvotes: 1

Related Questions