Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Echo integer on the same output line while it's being incremented?

I have always wondered if it's possible to do the following in PHP:

for($x = 1; $x <= 50; $x++)
    echo $x;

this would output:

1234 etc...

Obviously it wouldn't be this code specifically since it would be almost instantaneous and you wouldn't even be able to see the incrementation take place. Now to my question: would it be possible to echo it, remove it, repeat? Simply put the output should be on the same line from start to finish. I don't know how to explain it or show, but here is an example (somewhat):

1 (backspace) 2 (backspace) etc...

I hope you can understand it, I don't know how else to explain it .-.

Thank you for the help!

EDIT: This is for console by the way, sorry I forgot to include that. This isn't for the web!

like image 876
user1488335 Avatar asked Aug 02 '12 15:08

user1488335


3 Answers

If you run your code in CLI :

echo $x."\r";
like image 146
Chibani Avatar answered Oct 23 '22 16:10

Chibani


With the usual php's output goes to HTTP response setup no, its not possible. Everything that shows up on the user's screen is gone trough the network and you can't control it anymore.

But if you are running in a CLI environment there are full character based window drawing libraries, like ncurses that you can use to move pixels (in this case characters) around in your terminal.

like image 33
complex857 Avatar answered Oct 23 '22 14:10

complex857


You could do that with Javascript fairly easily, but since PHP genereates the page and then sends it away, it wouldn't be something you could use PHP for directly, at least if your end intent is allowing the user to see the changes as they occur.

Edit: This was on the assumption you were on the web, so not sure since you updated the question to relate to the console instead.

like image 1
Gyhth Avatar answered Oct 23 '22 15:10

Gyhth