Jump to content


Photo

Running a line only once in a for loop


  • Please log in to reply
3 replies to this topic

#1 witt

witt
  • Members
  • PipPipPip
  • Advanced Member
  • 36 posts

Posted 29 May 2006 - 04:38 AM

Let's say I have this code

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

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

#2 samshel

samshel
  • Members
  • PipPipPip
  • Advanced Member
  • 837 posts

Posted 29 May 2006 - 08:03 AM

$flag=0;
for ($i = 0; $i < $counter; $i++) {
echo "hi";
  if($flag == 0) {
    $flag=1;
    echo "done";
  }
}


But..perhaps..if you want to display it only once, why do you need to keep it in for loop.....
Cheers,
SamShel
-----------------------------------------------
--: FUTURE IS LINUX :--
-----------------------------------------------

#3 glenelkins

glenelkins
  • Members
  • PipPipPip
  • Advanced Member
  • 760 posts
  • LocationBridlington - East Riding of Yorkshire - United Kingdom

Posted 29 May 2006 - 10:05 AM

Good Question witt!! lol
http://thewebsolutionprovider.com - A Solution For Everything Web!

#4 kenrbnsn

kenrbnsn
  • Staff Alumni
  • Advanced Member
  • 8,235 posts
  • LocationHillsborough, NJ, USA

Posted 29 May 2006 - 01:39 PM

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:
<?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
//
}?>
Ken




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users