Skip to content

Instantly share code, notes, and snippets.

@davidthingsaker
Created July 21, 2015 10:17
Show Gist options
  • Save davidthingsaker/ff5366b8ae8def45a8c3 to your computer and use it in GitHub Desktop.
Save davidthingsaker/ff5366b8ae8def45a8c3 to your computer and use it in GitHub Desktop.
Human readable data sizes in PHP
# Pass in the level of accuracy and optionally if you are talking about speed. Which will add a per seconds suffux.
public static function human_datasize($bytes, $decimals = 2, $speed = false)
{
$sz = 'BKMGTP';
if(is_null($bytes)) {
return 'Unlimited';
}
if ($speed) {
$suffix = 'bps';
} else {
$suffix = 'B';
}
$factor = floor((strlen($bytes) - 1) / 3);
$str = sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
if(substr($str, -1) !== 'B') {
$str = $str . $suffix;
}
return $str;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment