Skip to content

Instantly share code, notes, and snippets.

@ivo-ivanov
Created April 6, 2020 16:40
Show Gist options
  • Save ivo-ivanov/daafbd8a7d95100606ccb30ed6b89a25 to your computer and use it in GitHub Desktop.
Save ivo-ivanov/daafbd8a7d95100606ccb30ed6b89a25 to your computer and use it in GitHub Desktop.
Format bytes #php
// format bytes in KB/MB
function formatBytes($bytes, $precision = 0) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
// $bytes /= pow(1024, $pow);
$bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . '' . $units[$pow];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment