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.

My point was that you can often change the logic so a different action is taken on a known first item rather than an unknown last item.

 

In the absence of info about what s/he is doing I just used that as an example.

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.

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>';
  } 
?>

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?

In that situation yes...however I did mention that the if the loop is iterative in nature it will never be reached ... meaning a continuous function rather than the discrete values generated by rand

Archived

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

×
×
  • 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.