Skip to content

Instantly share code, notes, and snippets.

@jasonhofer
Last active September 19, 2018 20:39
Show Gist options
  • Save jasonhofer/6a2a647fb6853799167c8e165c17673c to your computer and use it in GitHub Desktop.
Save jasonhofer/6a2a647fb6853799167c8e165c17673c to your computer and use it in GitHub Desktop.
<?php
/**
* Show a status bar in the console.
*
* <code>
* for ($x = 1; $x <= 100; ++$x) {
* show_status($x, 100);
* usleep(100000);
* }
* </code>
*
* Source: https://stackoverflow.com/questions/2124195/command-line-progress-bar-in-php
*
* @param int $done how many items are completed
* @param int $total how many items are to be done total
* @param int $size optional size of the status bar
*/
function consoleProgress($done, $total, $size = 30) {
static $startTime;
// if we go over our bound, just ignore it
if ($done > $total) return;
if (empty($startTime)) {
$startTime = time();
}
$now = time();
$perc = (float) ($done / $total);
$bar = floor($perc * $size);
$statusBar = "\r[";
$statusBar .= str_repeat("=", $bar);
if ($bar < $size) {
$statusBar .= ">";
$statusBar .= str_repeat(" ", $size - $bar);
} else {
$statusBar .= "=";
}
$disp = number_format($perc * 100, 0);
$statusBar .= "] {$disp}% {$done}/{$total}";
$rate = ($now - $startTime) / $done;
$left = $total - $done;
$eta = round($rate * $left, 2);
$elapsed = $now - $startTime;
$statusBar .= ' remaining: ' . number_format($eta) . ' sec. elapsed: ' . number_format($elapsed) . ' sec. ';
echo $statusBar;
flush();
// when done, send a newline
if ($done === $total) {
echo "\n";
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment