Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

echo/print issue in php while loop

I need a fix for this.
here is just part of my code

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

}
?> 

The loop process in the loop is actually much bigger, i just put the important stuff.

Anyways as you can see it should print
30 posted
(wait 30 seconds)
29 Posted
(wait 30 seconds)
28 Posted
(wait 30 seconds)

But instead it waits till the loop is over, then just prints it all at once. Is there a fix for this? I was thinking an ajax method, but I dont know of any.

like image 470
Joseph Robidoux Avatar asked Mar 04 '10 19:03

Joseph Robidoux


3 Answers

Nice that everyone explained why.

This is because by default PHP will process everything before it 'flushed' anything out to the browser. By just printing each line, it's storing that information in the buffer which will all be printed simultaneously once PHP is finished executing.

If you want PHP to flush that content to the browser immediately after the line, you need to call flush() after each one, then it will output the text one line at a time after each one is called.

like image 79
animuson Avatar answered Nov 14 '22 14:11

animuson


Call flush() after printing.

like image 44
Ignacio Vazquez-Abrams Avatar answered Nov 14 '22 14:11

Ignacio Vazquez-Abrams


You need to use flush()

like image 2
jtm Avatar answered Nov 14 '22 14:11

jtm