Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Output two lines separately to the console in PHP

I have written this small PHP script which counts from 0 to 9 while also showing the sum of the counted numbers.

<?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 see, on each iteration, I am cleaning up the line (8 is the ASCII code for backspace) and showing the new text in the same line.

This works fine, but now I want to show the Count and the Total in two different lines and animate the two lines in the same way that 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 issue here is that backspace stops at the \n character and so it deletes the second line but leaves the first line as it is 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 ?

Thanks

like image 725
webNeat Avatar asked Aug 22 '16 19:08

webNeat


2 Answers

I finally found a working soution:

<?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 takes benefit from some ansicodes, check This document for more details.

Thanks @Joshua Klein for help.

like image 98
webNeat Avatar answered Nov 01 '22 15:11

webNeat


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) or different ansicodes characters which you can read about here:
Clear PHP CLI output

like image 1
Joshua Klein Avatar answered Nov 01 '22 17:11

Joshua Klein