|
Convert Bytes to corresponding size II
| Author | vladan |
| Description | Improved mkeefe's version of "Convert Bytes to corresponding size"
Takes a number in bytes and returns the number in (B, KB,MB,GB, TB) for human-readable format.
If second parameter is set, returns desired unit ('B' is default).
Recursive.
|
| Rating | (0 votes) |
PHP Code
function byteSize($size, $unit = null, $decimals = 1, $thousands_sep = " ") {
# bytesize units
static $units = array('B', 'KB', 'MB', 'GB', 'TB');
# default / actual unit
static $actual = 'B';
# index of a unit
$index = array_search($actual, $units);
# dynamic unit || chosen unit || max unit
if (($unit == null && $size < 1024) || $unit === $actual || $index == sizeof($units)-1) {
$decimals = ($size < 1024 && $actual != 'B' ? (int) $decimals : 0);
# backup actual unit
$unit = $actual;
# restore default unit (static variable)
$actual = 'B';
return number_format($size, $decimals, ".", $thousands_sep) . " " . $unit;
} else {
# shift actual unit
$actual = $units[$index+1];
return byteSize($size / 1024, $unit, $decimals, $thousands_sep);
}
}
Comments
No comments posted yet.
|