I want something like:
for($k=0;$k<20;$k++){
echo $k;
}
Output:
0
Sleep for 1 second.
1
sleep for 1 second.
2
sleep for 1 second.
.
. .
I want something like:
for($k=0;$k<20;$k++){
echo $k;
}
Output:
0
Sleep for 1 second.
1
sleep for 1 second.
2
sleep for 1 second.
.
. .
If you're interested in having the variables appear on the page one by one, with a second delay in between, you'll need to use JavaScript rather than PHP. If you need input from PHP, use Ajax.
PHP has an inbuilt function called sleep()
(http://php.net/manual/en/function.sleep.php) that causes the code to delay for a given number of seconds. However, this will not have the behaviour you might expect, which is to say, echoing a variable, then waiting a second, then echoing another one. The script will simply take that many seconds longer to execute.
So, for example:
for($k=0;$k<20;$k++){
echo $k;
sleep(1);
}
Will take 20 seconds to execute, but the page will still only load once.
I think you're looking for output buffer:
for ($k = 0; $k < 20; $k++) {
echo $k . '<br />';
flush();
ob_flush();
sleep(1);
}
If you intend to do this at CLI, then you need to use sleep, like this
for($k=0;$k<20;$k++){
echo $k.'<br>Sleep for 1 second.';
sleep(1);
}
However, if you intend to do this at the web-browser, then PHP runs at the server before the server responds to the client, therefore all your 20 seconds are spent on the server and the browser will receive all the output at once. Therefore, for browsers your approach is not adequate, instead of that, you might want to do a polling, or a setTimeout, or a setInterval. Since you are interested in PHP loops, I would like to suggest that you could run your PHP from command-line.
use inbuilt sleep function //time in seconds
for($k=0;$k<20;$k++){
echo $k;
sleep(1);
}
From http://docs.php.net/Thread with pthreads
<?php
class workerThread extends Thread {
public function __construct($i){
$this->i=$i;
}
public function run(){
while(true){
echo $this->i;
sleep(1);
}
}
}
for($i=0;$i<50;$i++){
$workers[$i]=new workerThread($i);
$workers[$i]->start();
}