3

I have foreach functions that print students names

$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   sleep(3);
}

How can i print each name, each 3 seconds? After "echo $name" i need some timer to stop the loop and wait for 3 seconds. sleep() functions doesn't work here. What else i can do?

2
  • look on ob_flush() and flush() Commented Jul 27, 2011 at 13:17
  • Is this on the command line or on a web page? Commented Jul 27, 2011 at 13:18

5 Answers 5

4

You can not do this server side (reliably). This is because there is just too much possibility of your traffic being held or buffered on the way: by the webserver, by proxies along the way, by your browser, etc. It would however probably work on CLI.

So I would definitely do it client-side, without sacrificing security (if needed).

If this is only for "cosmetic" purposes, you can create an AJAX method which will return the array of names, and then have Javascript output them with its timers.

Or, you could have AJAX call the PHP script using timers, and PHP will return only one name. It can save the current timestamp in the DB or in a Session variable, and don't return a new name until some time has passed.

Sign up to request clarification or add additional context in comments.

Comments

3

try using flush function

ob_start();    
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   ob_flush();
   flush();    
   sleep(10);
}

Comments

1

If you need to do this in a web page you need to flush the output or disable output buffering to get that work. Some references:

In php CLI that code will work.

Comments

1

You can do this with javascript, ajax

or with flush() function

<?php
$names = array("Alex","Brad","Tom");
foreach($names as $name) {
   echo "$name <br />";
   flush();
   sleep(3);
}

working demo

11 Comments

That's not true. You can do that, even if I think it's a bad practice.
@Fabio: It works for me in one server but not on second. How is it possible?
It depends on your php.ini configuration, try to add also an ob_flush() call.
look on php.ini php_value output_buffering "0"
Because in your first answer you've said that is not possible.
|
0

You can write flush(); after echo

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.