Skip to content

Instantly share code, notes, and snippets.

@andyexeter
Created January 22, 2017 15:05
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 andyexeter/5aae0c7a2138cf36dc21bcd2c5f513d6 to your computer and use it in GitHub Desktop.
Save andyexeter/5aae0c7a2138cf36dc21bcd2c5f513d6 to your computer and use it in GitHub Desktop.
sizeFormat function for PHP - Extracted from WordPress core
<?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