0
 echo "counter: ";
 $i=1;
 while ($i <= 5) {
    print($i);
    sleep(1);
    $i++;
 }

The above will output: counter: 12345 I need to output eg.: loop 3 - counter: 3 (one digit per loop)

How to do it:

1) When running in a browser?

2) When running from command line (php index.php)?

3
  • What is difference of your loop and counter? Can you explain more detailed please? Commented May 9, 2017 at 8:24
  • 1
    I'm not sure what you asking for to explain. This is just an example of while loop. Commented May 9, 2017 at 8:32
  • You need to use java-script at browser, to update any div in 1st iteration counter: 1 2nd iteration counter: 2 and so on. Commented May 9, 2017 at 8:35

2 Answers 2

1

I think you want to make an auto-updated string. It's impossible to make it with only PHP. You should use Javascript (or a library like jQuery) and send the data from PHP via Ajax call.

You can even do this only with Javascript.

var counter = 1;
setInterval(function () {
  counter++;
}, 5);

For command line you can use your code with "\r" at the end of the string.

$i=0;
while ($i <= 5) {
   sleep(1);
   $i++;
   echo "counter: $i\r";
}
Sign up to request clarification or add additional context in comments.

1 Comment

well, I want to do a few operations on database in one loop, so this should be as simple it can be. What would be the answer for question 2?
0

I think this is what you need. The counter string was brought inside the loop and a break was added for a new line simulation. Also the < was changed to <= as the loop was running for 4 times instead of 1.

 $i=1;
 while ($i <= 5) {
 print("counter: $i <br>");
 sleep(1);
 $i++;
 }

1 Comment

No this not what I expect. I need to see one digit on the screen at the time. So counter: 3 if it is loop 3 (no more digits). It should like clear old digit every loop.

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.