Echo 'string' while every long loop iteration (flush() not working)

Viewed 30017

I have a loop that takes very long to execute, and I want the script to display something whenever the loop iteration is done.

echo "Hello!";

flush();

for($i = 0; $i < 10; $i ++) {
    echo $i;
    //5-10 sec execution time
    flush();
}

This does not display the echos until the entire script is completed. What went wrong?

7 Answers

Add this on the header of the script:

ob_start();
ob_implicit_flush();

Implicit flushing will result in a flush operation after every output call so that explicit calls to flush() will no longer be needed. Please note that adding implicit flushing in the script execution affects on performance. You can add a debugging mode for your script like:

ob_start();
define(DEBUG, 1);

if(DEBUG){
    ob_implicit_flush();
}
Related