php 在第一个循环的 while 循环中显示一次文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/831501/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Display text once within while loop on the first loop
提问by Brad
<?php
$i = 0;
while(conditionals...) {
if($i == 0)
print "<p>Show this once</p>";
print "<p>display everytime</p>";
$i++;
}
?>
Would this only show "Show this once" the first time and only that time, and show the "display everytime" as long as the while loop goes thru?
这是否仅在第一次且仅在该次显示“显示一次”,并且只要 while 循环通过就显示“每次显示”?
回答by pts
Yes, indeed.
确实是的。
You can also combine the if and the increment, so you won't forget to increment:
您还可以将 if 和 increment 结合使用,这样您就不会忘记增加:
if (!$i++) echo "Show once.";
回答by Sumeet Chawla
Rather than incrementing it every time the loop runs and wasting useless resource, what you can do is, if the value is 0 for the first time, then print the statement and make the value of the variable as non-zero. Just like a flag. Condition, you are not changing the value of the variable in between the loop somewhere. Something like this:
与其在每次循环运行时都增加它并浪费无用的资源,您可以做的是,如果第一次值为 0,则打印语句并将变量的值设为非零。就像一面旗帜。条件,您没有在某处循环之间更改变量的值。像这样的东西:
<?php
$i = 0;
while(conditionals...) {
if($i == 0){
print "<p>Show this once</p>";
$i=1;
}
print "<p>display everytime</p>";
}
?>
回答by workmad3
Yes, as long as nothing in the loop sets $i back to 0
是的,只要循环中没有任何内容将 $i 设置回 0
回答by Nadia Alramli
Yes it will, unless the conditions are false from the start or $i was set to 0 inside the loop
是的,除非条件从一开始就为假或 $i 在循环内设置为 0

