Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display text once within while loop on the first loop

Tags:

php

while-loop

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

like image 200
Brad Avatar asked Nov 29 '22 20:11

Brad


2 Answers

Yes, indeed.

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

if (!$i++) echo "Show once.";
like image 165
pts Avatar answered Dec 06 '22 13:12

pts


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>";
   }
?>
like image 35
Sumeet Chawla Avatar answered Dec 06 '22 15:12

Sumeet Chawla