开发者

iterate echo total number

How could I ec开发者_运维问答ho the last number? it should be 9.

$i = 0;
while($i != 10){
    echo $i;
    $i++;
}


You want to echo just the last number?

$i=$j=0;
while($i!=10){
    $j=$i++;
}
echo $j;

Although this is a very bad way to do that, I'm only showing it because I believe you're doing something completely different with that code


if {$i = 9) {
echo "$i"; }

This should work, if you want you could have an array store variables, and then base the output on user input.


If you want to catch the last iteration, then take away the loops condition and handle it yourself:

while (true) {

    ...

    if (++$i == 9) {
        echo $i;
        break;
    }
}

If you bark at the break, then resort to a condition flag $last = $i == 9; instead.


You could just do the following:

echo 9;

If the last number is variable, you could do the following:

echo $last_number - 1;

If there's some weird requirement where you need to do a loop, and you really do need it to loop over all the other numbers before finally echoing the penultimate number, you could just check it every single iteration:

$i = 0;
$penult = $last_number - 1;
while ($i !== $last_number) {
    if ($i === $penult) {
        echo $i;
    }
    $i += 1;
}

...Or you could use continue:

$i = 0;
$penult = $last_number - 1;
while ($i !== $last_number) {
    if ($i !== $penult) {
        continue;
    }
    echo $i;
}


Placing the condition at the end, you prevent that $i gets updated when it shouldn´t anymore.

$i = 0;
do {
    $i++;
} while ($i != 10);
echo $i;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜