Skip to content

Instantly share code, notes, and snippets.

@sfaut
Created March 10, 2022 10:04
Show Gist options
  • Save sfaut/b32dc851831acd85a311dfccb03e4bdb to your computer and use it in GitHub Desktop.
Save sfaut/b32dc851831acd85a311dfccb03e4bdb to your computer and use it in GitHub Desktop.
Converts bytes to a readable value to nearest unit
<?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