php - Using sleep() function as timer with while loop is not working?

I want a while loop to echo the value of x every 5 seconds, until x is equal to 10, but using the sleep() function makes it echo all 10 values at the end of the loop, rather than one at a time every 5 seconds.

$x = 1;
while($x <= 10) {
  sleep(5);
  echo $x;
  $x++;
}

How do I get around this issue without having to use cron?

P.S. I need to run the script via web server, not console.

Answer

Solution:

It's expected behavior. Web-server does not send output to user as soon as it appears. Output will be sent to user, when script finish, not earlier. sleep() just makes script to run longer. If you need make some webpage, where lines appear dynamically, you need to use JavaScript. It's front-end task, not back-end.

Answer

Solution:

What you're seeing is a delay in the output reaching your browser, not a delay in the PHP code. By default, web servers will "buffer" output, sending the browser a chunk at a time rather than every byte individually.

You can change that (using flush() and ob_flush) but it sounds like that's not actually what you're trying to achieve. To make your experiment clearer, try echoing the time at each step:

$x = 1;
while($x <= 10) {
  sleep(5);
  echo (new DateTime)->format('H:i:s'), "<br>\n';
  $x++;
}

Although they all reach your browser at the same time, you will be able to see that the command actually ran spread out as you wanted.

Source