Jump to content

Archived

This topic is now archived and is closed to further replies.

witt

Running a line only once in a for loop

Recommended Posts

Let's say I have this code

[code]for ($i = 0; $i < $counter; $i++) {
echo "hi";
echo "done";
}[/code]

and I want to run the line echo "done"; only once. Is it possible withough moving it out of the for loop?

Share this post


Link to post
Share on other sites
[code]
$flag=0;
for ($i = 0; $i < $counter; $i++) {
echo "hi";
  if($flag == 0) {
    $flag=1;
    echo "done";
  }
}
[/code]


But..perhaps..if you want to display it only once, why do you need to keep it in for loop.....

Share this post


Link to post
Share on other sites
Good Question witt!! lol

Share this post


Link to post
Share on other sites
In the example given by the OP it doesn't make sense to have the second statement in the loop, but in real code, it might. Let's say the for loop is looping through a large array of information and you need to execute a unique piece of code once if some condition is met by the value in one element of the array, then the question makes sense and the for loop would be coded something like this:
[code]<?php
$flag = false;
for ($i=0;$i<count($the_array);$i++) {
//
//  do some work
//
      if ($the_array[$i] == 'some condition' && !$flag) {
           echo 'The condition has been met'; // do the one line -- it doesn't have to be an echo
           $flag = true;
      }
//
//   do some more work
//
}?>[/code]
Ken

Share this post


Link to post
Share on other sites

×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.