Skip to content

Instantly share code, notes, and snippets.

@malenkiki
Created November 13, 2020 22:27
Show Gist options
  • Select an option

  • Save malenkiki/5d91d15d4efa1f5c4010bc89bb33d079 to your computer and use it in GitHub Desktop.

Select an option

Save malenkiki/5d91d15d4efa1f5c4010bc89bb33d079 to your computer and use it in GitHub Desktop.
Format bytes as Ko, Go, and so on using PHP.
<?php
function byte_format($bytes, $precision = 2, $dec_point = '.')
{
// From https://stackoverflow.com/a/37523842
$units = ['o', 'Ko', 'Mo', 'Go', 'To'];
$bytes = max($bytes, 0);
$pow = min(
floor(($bytes ? log($bytes) : 0) / log(1024)),
count($units) - 1
);
$bytes /= pow(1024, $pow);
return sprintf(
'%s %s',
number_format($bytes, $precision, $dec_point, ''),
$units[$pow]
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment