Output two lines separately to the console in PHP

I wrote this small PHP script that counts from 0 to 9, and also shows the sum of the numbers counted.

<?php $sum = 0; $line = ''; for ($i=0; $i < 10; $i++) { $sum += $i; echo str_repeat(chr(8), strlen($line)); // cleaning the line $line = "Counter: {$i} | Total: {$sum}"; echo $line; // Outputing the new line sleep(1); } echo "\n"; 

As you can see, at each iteration, I clear the line ( 8 is the ASCII code for backspace ) and show the new text on the same line.

This works fine, but now I want to show Count and Total on two different lines and animate two lines in the same way as I did with one line. So I tried this code:

 <?php $sum = 0; $line = ''; for ($i=0; $i < 10; $i++) { $sum += $i; echo str_repeat(chr(8), strlen($line)); // cleaning the line $line = "Counter: {$i}\nTotal: {$sum}"; echo $line; // Outputing the new line sleep(1); } echo "\n"; 

The problem here is that backspace stops at the \n character and therefore deletes the second line, but leaves the first line, which gives the following output:

 Counter: 0 Counter: 1 Counter: 2 Counter: 3 Counter: 4 Counter: 5 Counter: 6 Counter: 7 Counter: 8 Counter: 9 Total: 45 

Is there a proper way to solve this problem?

thanks

+8
command-line-interface php
source share
2 answers

I finally found a working script:

 <?php $sum = 0; $line = ''; for ($i=0; $i < 10; $i++) { $sum += $i; $line = "Counter: {$i}\nTotal: {$sum}"; echo $line; // Outputing the new line sleep(1); echo chr(27) . "[0G"; // go to the first column echo chr(27) . "[1A"; // go to the first line echo chr(27) . "[2M"; // remove two lines } echo "Total: {$sum}\n"; 

This benefits from some ansicode, see this document for more details.

Thanks @Joshua Klein for the help.

+5
source share

Really lame answer (works on linux):

  <?php $sum = 0; $line = ''; for ($i=0; $i < 10; $i++) { $sum += $i; echo str_repeat(chr(8), strlen($line)); // cleaning the line $line = "Counter: {$i}\nTotal: {$sum}"; echo $line; // Outputing the new line sleep(1); system("clear"); } echo "\n"; 

The real answer has something to do with the \ r (linefeed) characters or other ansicodes you can read here:
Clear CLI output for PHP

+1
source share

All Articles