Jump to content

Running a line only once in a for loop


witt

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?
Link to comment
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
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

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.