PHP Front
The PHP website created by its users!
Home » PHP » Convert Bytes to corresponding size II


Convert Bytes to corresponding size II


Authorvladan
DescriptionImproved 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.
RatingThis script has been rated 0/5 (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);
    }
 }



Rate it: Print Print

Comments


No comments posted yet.

Name
Website
Your comment