有没有办法解决这个问题,最后没有空的{}


Is there a way to solve this without an empty {} at the end?

我正在学习PHP并尝试编写一个小骰子循环。我想知道如何用更合适的语法重写它:

<?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 {}
?>

如果它不执行任何操作,只需删除该 else 子句

 else {}

你甚至不需要这句if语句,因为只有当它们都相等时,控制权才会到达那里。

<?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.
?>

你不需要有一个 else 语句:

if ($v == $w) {
    echo "<p>It took $rollcount turns until double!</p>";
}

如果事实上,除非它要执行一组特定的任务,否则你不应该有一个。

$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>";