As some of you might already know, I make great use of the Command Line Interface (CLI) of PHP for tasks or tools that need to be run incidentally or periodically.
For tasks that have iterations in them (like while or foreach -loops) I like to have a visual feedback in my terminal of the progress. For example:
- What’s the total number of iterations?
- What’s the current iteration?
- How many percent is already done?
- How much longer does it take?
- How much memory is PHP currently consuming?
I created a very simple function to provide this feedback. It’s output looks a bit like this:
Today I’m going to share this function with you.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
$epStarttime = 0; /** * Show progress bar * @param $current * @param $total */ function echoProgress($current, $total) { global $epStarttime; $percent = $current / $total; $p = $percent * 100; // Set starttime: if($percent == 0 || $current == 1) { $epStarttime = time(); } $p2 = floor($p / 2); $progress = str_pad('', $p2, '=') . str_pad('', 50 - $p2); $usage = round(memory_get_usage() / 1024, 1); /// Show progressbar: echo "Progress: [" . $progress . "] " . number_format($p, 2) . "% - "; // Show count: if($current !== null && $total !== null) { echo "[" . $current . "/" . $total . "] - "; } // Show ETA: $elapsedSeconds = time() - $epStarttime; $etaSeconds = (1 - $percent) * ($elapsedSeconds / $percent); echo "ETA: " . date('H:i:s', $etaSeconds) . " - "; // Show memory usage: echo "MEM: " . $usage . "k \r"; if($percent == 1) { unset($epStarttime); echo "\n"; } } |
The function is called: echoProgress() , and it takes 2 parameters:
- The number of the current iteration.
- The number of the total amount of iterations that are being executed.
Once called within your while() , foreach() or whatever iteration structure you’re using, it echo’s the current status to the terminal. Please note that it ends it’s line with \r and not with \n . This little trick makes sure you’re seeing a nice little progress bar instead of thousands of lines being spit out.
Use it as you please. I know I do!
Visitors give this article an average rating of 4.3 out of 5.
How would you rate this article?
★ ★ ★ ★ ★