Created
January 22, 2017 15:05
-
-
Save andyexeter/5aae0c7a2138cf36dc21bcd2c5f513d6 to your computer and use it in GitHub Desktop.
sizeFormat function for PHP - Extracted from WordPress core
This file contains hidden or 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 | |
/** | |
* Convert number of bytes largest unit bytes will fit into. | |
* Extracted from WordPress core to work as a standalone function. | |
* | |
* @link https://codex.wordpress.org/Function_Reference/size_format | |
* | |
* @param int|string $bytes Number of bytes. Note max integer size for integers. | |
* @param int $decimals Optional. Precision of number of decimal places. Default 0. | |
* | |
* @return string|false False on failure. Number string on success. | |
*/ | |
function sizeFormat( $bytes, $decimals = 0 ) { | |
$quant = array( | |
'TB' => 1e+12, | |
'GB' => 1073741824, | |
'MB' => 1048576, | |
'kB' => 1024, | |
'B' => 1, | |
); | |
foreach ( $quant as $unit => $mag ) { | |
if ( doubleval( $bytes ) >= $mag ) { | |
return number_format( $bytes / $mag, $decimals ) . ' ' . $unit; | |
} | |
} | |
return false; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment