Skip to content

Instantly share code, notes, and snippets.

@leMaur
Last active June 30, 2020 09:39
Show Gist options
  • Save leMaur/14740d869683e26c8bd4f3d0c485e0da to your computer and use it in GitHub Desktop.
Save leMaur/14740d869683e26c8bd4f3d0c485e0da to your computer and use it in GitHub Desktop.
if (! function_exists('human_readable_bytes')) {
/**
* Convert bytes in a human readable value.
*
* According to the specifications, for storage purpose use "metric" system.
*
* @see https://stackoverflow.com/a/38659168
* @see https://en.wikipedia.org/wiki/Binary_prefix
* @param string $bytes
* @param int $decimals
* @param string $system
* @return string
*/
function human_readable_bytes(string $bytes, int $decimals = 2, string $system = 'metric'): string
{
if (! in_array($system, ['binary', 'metric'])) {
$system = 'metric';
}
$mod = ($system === 'binary') ? 1024 : 1000;
$units = array(
'binary' => ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB', 'EiB', 'ZiB', 'YiB'],
'metric' => ['B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'],
);
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f%s", ((float) $bytes / ($mod ** $factor)), $units[$system][$factor]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment