Created
March 10, 2022 10:04
-
-
Save sfaut/b32dc851831acd85a311dfccb03e4bdb to your computer and use it in GitHub Desktop.
Converts bytes to a readable value to nearest unit
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 | |
/** | |
* Return the $bytes to the nearest unit (1 kB = 1,000 B) | |
* eg. human_size(1_000) => "1 kB" | |
* eg. human_size(876543210, 1) => "876.5 MB" | |
*/ | |
function human_size( | |
int $bytes, int $precision = 0, int $base = 1_000, | |
array $units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] | |
) { | |
$factor = floor(log($bytes, $base)); | |
if (!isset($units[$factor])) { | |
return "{$bytes} {$units[0]}"; | |
} | |
return sprintf( | |
"%.{$precision}f %s", | |
$bytes / pow($base, $factor), | |
$units[$factor], | |
); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment