Skip to content

Instantly share code, notes, and snippets.

@Clicketyclick
Forked from mayconbordin/progress_bar.php
Last active February 28, 2024 02:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Clicketyclick/7803adb4b2b3da6ec1b7c9b1f29d9552 to your computer and use it in GitHub Desktop.
Save Clicketyclick/7803adb4b2b3da6ec1b7c9b1f29d9552 to your computer and use it in GitHub Desktop.
PHP CLI progress bar in 5 lines of code
<?php
/**
* @brief Return a progress bar with the length of $width
*
* @param [in] $done count for progress
* @param [in] $total Maximum of progress
* @param [in] $info Prefix text
* @param [in] $width Width of progress bar (w/o prefix)
* @param [in] $off Char to indicate not processed yet
* @param [in] $on Char to indecate process
* @return Return progress bar
*
* @details
* @example
* $max = 40; // Max in loop
* $overflow = 60; // Overflow in loop
* $total = 50; // Total count
* $width = 50; // Width of processbar
*
* print( "\nSimple test with [#_]\n");
* for ( $x = 0; $x <= $max ; $x+=10) {
* print progress_bar( $x, $total, "test", $width );
* sleep(1);
* }
*
* foreach ( [
* '░' => '█'
* , '.' => 'X'
* , html_entity_decode('&#x2592;', 0, 'UTF-8') => html_entity_decode('&#x2588;', 0, 'UTF-8')
* , '-' => '/'
* ] as $off => $on ) {
* print "\n[$off][$on]\n";
* for ( $x = 0; $x <= $max ; $x+=10) {
* print progress_bar( $x, $total, "test", $width, $off, $on );
* sleep(1);
* }
* }
*
* print( "\nOverflow test with [#_]\n");
* for ( $x = 0; $x <= $overflow ; $x+=10) {
* print progress_bar( $x, $total, "test", $width );
* sleep(1);
* }
*
*
* Will produce:
* Simple test with [#_]
* test [########################################__________] 80% 40/50
* [░][█]
* test [████████████████████████████████████████░░░░░░░░░░] 80% 40/50
* [.][X]
* test [XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX..........] 80% 40/50
* [▒][█]
* test [████████████████████████████████████████▒▒▒▒▒▒▒▒▒▒] 80% 40/50
* [-][/]
* test [////////////////////////////////////////----------] 80% 40/50
* Overflow test with [#_]
* test [##################################################] 120% 60/50
*
* URL: https://gist.github.com/mayconbordin/2860547
*/
function progress_bar($done, $total, $info="", $width=50, $off = '_', $on = '#' ) {
$perc = round(($done * 100) / $total);
$bar = round(($width * $perc) / 100);
if ( $bar > $width ) // Catch overflow where done > total
$bar = $width;
return sprintf("%s [%s%s] %3.3s%% %s/%s\r"
, $info, str_repeat( $on, $bar)
, str_repeat( $off, $width-$bar), $perc, $done, $total);
} //*** progress_bar() ***
?>
@Clicketyclick
Copy link
Author

Added Doxyit header and reformatted output

@Clicketyclick
Copy link
Author

Updated with overflow test and dynamic characters in bar

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment