The Codesee
The Codesee

Reputation: 3783

Display result after each loop

In the code below, a url variable is increasing by 1 every time in a while loop. When $i is equal to 1000, the loop will end and $i will be displayed (from 1 all the way to 1000).

How do I display the value of $i after every loop, rather than waiting to the end?

$i = 1;
while($file = file_get_contents('http://example.com?id='.$i)) {
    if($i !== 1000) {
            echo $i;
    }else{
        break;
    }
    $i++;
}

Upvotes: 0

Views: 243

Answers (3)

Asmir Zahirovic
Asmir Zahirovic

Reputation: 267

You will need to flush message after each iteration. That way your browser will receive part of the information even if your request/response is still pending.

ob_implicit_flush(true);

$i = 1;
while($file = file_get_contents('http://example.com?id='.$i) && $i < 1000)
{
    echo $i;
    $i++;
    ob_flush();
    flush();
}

ob_end_flush();

Upvotes: 2

Kaff1n8t3d
Kaff1n8t3d

Reputation: 81

PHP happen on the server. To see each value for $i immediately you would need to make the server:

  1. do it's thing -> display that thing -> reload.

you can reload with header() but that is limited to 20 reloads (I think) unless you use header("Refresh:0");

I would make it display by making a stacking condition.

   if(isset($diplay)){//2+ times through
      $display = $display . $i . "<br>";
   }else{//first time through
      $diplay = $i."<br>";
   }

then put that inside your condition

if($i !== 1000) {
   if(isset($diplay)){
      $display = $display . $i . "<br>";
   }else{
      $diplay = $i."<br>";
   }
}else{
    break;
}

echo $display

echo $display;

Then increment your variable

$i++;

then refresh page and pass the variable at the same time.

header("Refresh:0; url=page.php?i=$i");

then you'll have to add a condition at the beginning that gets $i or assign it if not found.

if(isset($_GET['i'])){//meaning if it's found in the url like so ?i=$i
  $i = $_GET['i'];
}else{//first time through
  $i = 1;
}

///////////////////putting it all together////////////////////////

if(isset($_GET['i'])){
  $i = $_GET['i'];
}else{
  $i = 1;
}

while($file = file_get_contents('http://example.com?id='.$i)) {
  if($i !== 1000) {
    if(isset($diplay)){
      $display = $display . $i . "<br>";
    }else{
      $diplay = $i."<br>";
    }
  }else{
     break;
  }
  echo $display;
  $i++;
  header("Refresh:0; url=page.php?i=$i");
}

Upvotes: 0

Patrick Moore
Patrick Moore

Reputation: 13354

Move echo $i; outside of the if() statement:

$i = 1;
while($file = file_get_contents('http://example.com?id='.$i)) {
if($i !== 1000) {
    //    echo $i;
}else{
    break;
}
    echo $i;
    $i++;
}

This scenario is surely better suited for for() loop instead of while()...

Upvotes: 0

Related Questions