Last active
April 21, 2018 16:27
-
-
Save cereal-s/0f23921f9ae1ec1889d9bb251ed7b8e5 to your computer and use it in GitHub Desktop.
Format bytes to KiB, MiB, GiB and TiB.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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