Jump to content

how can you tell when you are on the last iteration of a while() loop?


ngng

Recommended Posts

As wsantos points out, it's easy with a for loop as the number of iterations is known in advance, but not so straightforward with a while loop.

 

Depend on what you are doing.

 

If, say, you are composing a list of comma-separated items but don't want the comma after the final one, then you can do it by output the comma before the items but NOT before the first. You easily know when you are on the first.

Link to comment
Share on other sites

I just want to know when I reach the final loop.

 

You can get each part of your loop to dump a message; that way you can tell where you are in the loop:

 

echo "this part of the loop is being executed";

 

--or--

 

die("this part of the loop is being executed"); 

 

die is merely an unformatted version of echo.. with echo you could write

<?php
echo "<div style='background-color:#000000; color:#FFCD32;'>";
echo "this part of the loop is being executed";
echo "</div>";
?>

where as die(); would be just a message on the screen.

 

So you can then tell which stage of the loop you are at.

Link to comment
Share on other sites

Well its a classic case of a blurry context of the problem...LOL I even made a typo...

 

while($k=0;$k<=$limit;$k++)
{
  if($k=$limit-1)?echo "LAST LOOP";
}

 

Versus

 

for($k=0;$k<$limit;$k++)
{
  if($k=$limit-1)?echo "LAST LOOP";
}

 

or you can test for the exit condition

<?php
  
  $k = 0;
  while ( $k != 5) {
    $k = rand(1,9);  
    echo $k ;
    if ($k==5) echo " Last";
    echo  '<br>';
  } 
?>

 

In this situation it will work however technically the conditional statement inside the loop will not be reached if the while statement is iterative.  LOL...What is your exact problem ngng?

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.