Skip to content

Instantly share code, notes, and snippets.

@bryandidur
Last active September 19, 2019 14:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bryandidur/37bfe0c048f5faaf49b0e3f57c816cd4 to your computer and use it in GitHub Desktop.
Save bryandidur/37bfe0c048f5faaf49b0e3f57c816cd4 to your computer and use it in GitHub Desktop.
Overwriting Terminal Output PHP
/**
 * Print a text and overwrite it (on the output) on a next call (terminal use only).
 *
 * @param  string $text
 * @return void
 */
function print_overwriting(string $text): void
{
    static $isFirstCall = true;

    // Ensure that the last char is a line break.
    $textLastChars = substr($text, -strlen(PHP_EOL));
    $text = $textLastChars != PHP_EOL ? $text . PHP_EOL : $text;

    if ($isFirstCall) {
        print $text;
    } else {
        $textLines = count(explode(PHP_EOL, $text)) - 1;

        // print "\x0D"; // Move the cursor to the beginning of the line (same as "\r").
        // print "\x1B[2K"; // Erase the line.
        // print str_repeat("\x1B[1A\x1B[2K", $textLines); // Erase previous lines.
        // print $text;

        // One line approach.
        print "\x0D\x1B[2K" . str_repeat("\x1B[1A\x1B[2K", $textLines) . $text;
    }

    if ($isFirstCall) $isFirstCall = false;
}

$count = 1000;

for ($i = 1; $i <= $count; $i++) {
    $firstRun = $i == 100;

    if ($i % 100 == 0) {
        sleep(1);

        $text = "Count: {$count}" . PHP_EOL .
                  "Index: {$i}" . PHP_EOL .
                  "Index: {$i}" . PHP_EOL .
                  "Index: {$i}" . PHP_EOL .
                  "Index: {$i}" . PHP_EOL;
                  // You can add a number of lines as you want.

        print_overwriting($text);
    }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment