-3

I am trying to make a PHP loop with delay between the loop this doens't work

<?php
$i=0;
while(true) {
    $i++;
    echo $i;
    sleep(1);
}
?>

I am trying to get this as an output:

1
[wait 1 second]

2
[wait 1 second]

3
[wait 1 second]

4
[wait 1 second]

5
[wait 1 second]

6
[wait 1 second]

...
Zlatan Omerović
  • 3,863
  • 4
  • 39
  • 67

1 Answers1

0

Try using flush and ob_flush to send the output to the browser before the script is completed:

<?php
header( 'Content-type: text/html; charset=utf-8' );
$i=0;
while(true) {
  $i++;
  echo $i;
  flush();
  ob_flush();
  sleep(1);
}
?>
igorshmigor
  • 792
  • 4
  • 10
  • 1
    This does not provide an answer to the question. To critique or request clarification from an author, leave a comment below their post. - [From Review](/review/low-quality-posts/19259998) – SaganRitual Mar 28 '18 at 15:11
  • Does it not? @Zwarte Piet, have you tried my solution? Does it work for you? – igorshmigor Mar 29 '18 at 11:15
  • The review system doesn't show comments by default. It just shows the question. Your code here will give him exactly what he showed in the question, so it didn't look helpful. Now I see that he left out the most important part of the question, and put it in the comments. Soon, other reviewers will come through and see the same thing I did, and they will vote to delete your answer as I did, and you'll get a disagreeable auto-message again. So, in addition to asking OP to put me in my place, you might also consider asking OP to fix his question, so it looks like your answer really is an answer. – SaganRitual Mar 29 '18 at 11:29
  • I see nothing wrong with either the question or my answer. The OP wants to create a delayed output where something appears in the browser, then after a second more output and so on. Felt clear to me. My answer does just that. – igorshmigor Mar 29 '18 at 13:49
  • I've done my part in trying to help you, warning you of what is likely to happen. What you do with the information I have generously offered to you is none of my business. – SaganRitual Mar 29 '18 at 14:07