php command line change text output

I want to know is it possible to change some output for special php cli base application to change some value on terminal not echo new one. for example this is cli application.

#!/usr/bin/env php
<?php

$percent = 0;

for ($i = 0; $i <= 100; $i++) {

    echo $percent . "\n";

    sleep(1);

    $percent++;
}

/**
0
1
...
*/

It's a simple app to show the user the percentage. So we must update it after each loop in this example, rather than append it. I want to change percent not show new one.

Upvotes: 2

Views: 5208

Answers (3)

Gerald Schneider
Gerald Schneider

Reputation: 17797

use \r instead of \n. \r is a carriage return, it will jump back to the beginning of the line without a newline.

$percent = 0;
for ($i = 0; $i <= 100; $i++) {
    echo $percent . "\r";
    sleep(1);
    $percent++;
}

This is working on Windows, Linux and MacOS

Upvotes: 11

Oldskool
Oldskool

Reputation: 34867

Something like this should work for what you need (tested and verified on a Linux (CentOS) machine):

for ($percent = 0; $percent <= 100; $percent++) {
    echo $percent;
    sleep(1);
    // Print one or more backspaces, erasing current character(s)
    echo str_repeat("\x08", strlen($percent));
}

Upvotes: 2

arkascha
arkascha

Reputation: 42950

This actually depends on your terminal (emulator) type, not on the language used. Have a few tries using the backspace character (0x08) to 'erase' the current content, then output the new content.

Upvotes: 1

Related Questions