= [[php:start|PHP Overview]]
====== Console: Simple Progress Bar ======
Say you are running a loop in a console script, and you want to display the progress to the user.\\
It would be nice to have a progress bar.
Let's start to make this!
We will initialize our loop counting variables, and some configuration for the progress bar:
// This is the running variable:
$current = 0;
// This is the maximum number of items for the loop:
$count = 10;
// Normalized maximum of progress bar sections
// This will paint 20 progress characters for 100%
$progress_max = 10;
// Character for single progress count
$cDone = '+';
// Character for not yet done progress item
$cToDo = '.';
Start the loop:
while($current < $count) {
// Do calculations for each item here
}
Calculate the current progress:
// inside the loop, increment the counter
$current++;
// calculate the normalized progress counter
$progress = round($current/$count * $progress_max);
// Print progress
// e.g. 2/10 [++........]
fwrite(
STDERR, // Print to standard error
"\033[100D" // rewind back cursor position to left 100 positions on this line
.sprintf('% '.strlen($count).'d', $current) // left pad $current to length of $count string
."/$count "
"[" // left bracket for progress bar
.str_repeat($cDone, $progress) // print finished items characters
.str_repeat($cToDo, $progress_max - $progress) // print items to be done characters
.']' // left bracket for progress bar
);
And here is how the final result looks like:
0/10 [+.........]
5/10 [+++++.....]
10/10 [++++++++++]
Enjoy.