I'm learning PHP and trying to write a little dice loop. I wonder how to rewrite this in a more appropriate syntax:
<?php
$rollcount = 1;
do {
$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 {}
?>
You don't NEED to have an else statement:
if ($v == $w) {
echo "<p>It took $rollcount turns until double!</p>";
}
If fact, you shouldn't have one unless it is going to perform a specific set of tasks.
$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>";
Simply remove that else clause if it doesn't do anything
else {}
You don't even need that if
statement, because control will reach there only when they are both equal.
<?php
$rollcount = 1;
do {
$v = rand(1, 6);
$w = rand(1, 6);
$rollcount++;
echo "<p>$v, $w</p>";
}
while ($v != $w);
echo "<p>It took $rollcount turns until double!</p>"; // that `if` was no needed here. Its implied.
?>