php - Is there a way to avoid an empty else { } at the end? -


i'm learning php , try write little dice loop. wonder how rewrite in more appropriate syntax:

<?php     $rollcount = 1;      {         $v = rand(1, 6);         $w = rand(1, 6);         $rollcount++;         echo "<p>$v, $w</p>";     }     while ($v != $w);      if ($v == $w) {         echo "<p>it took $rollcount turns until double!</p>";     } else {} ?> 

$rollcount = 0; while(true){     ++$rollcount;     $v = rand(1,6);     $w = rand(1,6);     echo "<p>".$v.", ".$w."</p>";     if($v === $w){         break;     } } echo "<p>it took ".$rollcount." turns until double!</p>"; 

explanation

since goal achieve double, dice can continue rolling till condition reached.
while continues processing until condition false, in case condition can never false since supply boolean true value while(true) loop.
php (and many other languages) provide execution control structures break, continue common.
break allows jump out of loop , it's possible execute when condition reached within loop
continue on other hand doesn't throw out of loop rather, skips next iteration of loop, means continue encountered in loop, every other statement after [within loop] skipped , loop moves next iteration.

in case, have double, exit loop , print out number of rolls required reach double.

hope helps


Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -