witt Posted May 29, 2006 Share Posted May 29, 2006 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? Quote Link to comment https://forums.phpfreaks.com/topic/10680-running-a-line-only-once-in-a-for-loop/ Share on other sites More sharing options...
samshel Posted May 29, 2006 Share Posted May 29, 2006 [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..... Quote Link to comment https://forums.phpfreaks.com/topic/10680-running-a-line-only-once-in-a-for-loop/#findComment-39881 Share on other sites More sharing options...
glenelkins Posted May 29, 2006 Share Posted May 29, 2006 Good Question witt!! lol Quote Link to comment https://forums.phpfreaks.com/topic/10680-running-a-line-only-once-in-a-for-loop/#findComment-39909 Share on other sites More sharing options...
kenrbnsn Posted May 29, 2006 Share Posted May 29, 2006 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 Quote Link to comment https://forums.phpfreaks.com/topic/10680-running-a-line-only-once-in-a-for-loop/#findComment-39933 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.