Display text once within while loop on the first loop

守給你的承諾、 提交于 2019-12-03 07:58:19

问题


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


回答1:


Yes, indeed.

You can also combine the if and the increment, so you won't forget to increment:

if (!$i++) echo "Show once.";



回答2:


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:

<?php

   $i = 0;

   while(conditionals...) {

      if($i == 0){
        print "<p>Show this once</p>";
        $i=1;
      }

      print "<p>display everytime</p>";
   }
?>



回答3:


Yes, as long as nothing in the loop sets $i back to 0




回答4:


Yes it will, unless the conditions are false from the start or $i was set to 0 inside the loop



来源:https://stackoverflow.com/questions/831501/display-text-once-within-while-loop-on-the-first-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!