Created
April 20, 2023 09:44
-
-
Save crispy-computing-machine/ebd7e546708dfe6c0b6878c6060e8bee to your computer and use it in GitHub Desktop.
PHP Progress bar
This file contains 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 | |
function displayProgressBar(int $current, int $total): void { | |
$width = 50; // The width of the progress bar | |
$percent = (int)(($current / $total) * 100); | |
$progress = (int)(($current / $total) * $width); | |
// Build the progress bar string | |
$progressBar = '['; | |
for ($i = 0; $i < $width; $i++) { | |
if ($i < $progress) { | |
$progressBar .= '='; | |
} elseif ($i === $progress) { | |
$progressBar .= '>'; | |
} else { | |
$progressBar .= ' '; | |
} | |
} | |
$progressBar .= ']'; | |
// Print the progress bar with the percentage | |
printf("\r%s %d%%", $progressBar, $percent); | |
// If the task is complete, print a newline | |
if ($current === $total) { | |
echo PHP_EOL; | |
} | |
} | |
// Example usage: | |
$total = 100; | |
for ($i = 0; $i <= $total; $i++) { | |
displayProgressBar($i, $total); | |
usleep(50000); // Sleep for 50ms to simulate progress | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment