-
-
Save Clicketyclick/7803adb4b2b3da6ec1b7c9b1f29d9552 to your computer and use it in GitHub Desktop.
PHP CLI progress bar in 5 lines of code
This file contains hidden or 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 | |
/** | |
* @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('▒', 0, 'UTF-8') => html_entity_decode('█', 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() *** | |
?> |
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
Added Doxyit header and reformatted output