Last active
August 21, 2018 16:29
-
-
Save CaduEspindola/b3779daa1f3062d6805896abdaeb7bba to your computer and use it in GitHub Desktop.
Progress indicator (percent) in command-line PHP script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Progress indicator (percent) in command-line PHP script (cmd) | |
* It only works in command line! | |
* Run: php ./progress-command-line.php | |
* @author Cadu Espindola <[email protected]> | |
*/ | |
$data = array('foo', 'bar', 'baz', 'foo', 'bar', 'baz'); | |
// or $data = array_fill(0, 90, 'foo'); | |
$percent = 0; | |
$step = 100 / count($data); | |
print "Loading: 0.00%"; | |
// ^-----^ place to print percent (7D) | |
foreach ($data as $subdata) { | |
// do stuff with data | |
sleep(1); | |
// progress indicator | |
print "\033[7D"; // return to replace percent (7D) | |
print str_pad(number_format(($percent += $step), 2), 6, ' ', STR_PAD_LEFT) . '%'; | |
flush(); | |
} | |
print PHP_EOL; | |
// That's it! :) | |
// Have a nice day! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment