Echo / print problem in php while loop

I need to fix this.
here is only part of my code

<?php $number = 30; while($number > 0) { $number--; sleep(30); print "$number . Posted<br>"; } ?> 

The cycle process in a cycle is actually a lot more, I just put the important stuff.

In any case, as you can see, it should print 30 messages
(wait 30 seconds)
29 Added | (wait 30 seconds)
28 Added | (wait 30 seconds)

But instead, it waits until the cycle ends, and then simply prints everything at once. Can this be fixed somehow? I was thinking about ajax method, but I don't know anything.

+6
ajax loops php while-loop echo
source share
5 answers

It's nice that everyone explained why.

This is because, by default, PHP will process everything before it reddenes something in the browser. By simply printing each line, it will save this information in a buffer that will be printed at the same time as soon as PHP finishes executing.

If you want PHP to run this content in the browser immediately after the line, you need to call flush() after each of them, then it will print the text one line at a time after calling each of them.

+15
source share

Call flush() after printing. A.

+4
source share

You need to use flush ()

+2
source share

Example loop with flush () -

 <?php ob_start(); for ($i = 0; $i < 10; $i++) { echo "<div>" . time() . ": Iteration $i</div>"; sleep(1); ob_flush(); flush(); } ob_end_flush(); ?> 

You should not hide often because you force php to process messages and this will increase the runtime.

+1
source share

You can put \n in echo or print to clear the buffer.

0
source share

All Articles