Skip to content

Instantly share code, notes, and snippets.

@cereal-s
Last active April 21, 2018 16:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cereal-s/0f23921f9ae1ec1889d9bb251ed7b8e5 to your computer and use it in GitHub Desktop.
Save cereal-s/0f23921f9ae1ec1889d9bb251ed7b8e5 to your computer and use it in GitHub Desktop.
Format bytes to KiB, MiB, GiB and TiB.
<?php
if( ! function_exists('_format_size'))
{
/**
* Return formatted bytes.
*
* @see http://www.iec.ch/si/binary.htm
* @param integer $bytes
* @param integer $kilo 1000, 1024
* @return string
*/
function _format_size($bytes, $kilo = 1000)
{
if(1024 == $kilo)
{
$m = [' bytes', 'KiB', 'MiB', 'GiB', 'TiB'];
}
else
{
$m = [' bytes', 'KB', 'MB', 'GB', 'TB'];
}
$s = array_reduce($m, function($a, $b) use($kilo) {
if(is_numeric($a))
{
if($kilo <= $a)
return $a / $kilo;
else
return number_format($a, 2) . $b;
}
else
return $a;
}, $bytes);
return $s;
}
}
$len = 10000000000;
print _format_size($len, 1000) . PHP_EOL; // 10.00GB
print _format_size($len, 1024) . PHP_EOL; // 9.31GiB
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment