format size

Snippet for formatting byte size.

function formatSize($size, $round = 0) {
    $sizes = array(‘B’, ‘kB’, ‘MB’, ‘GB’, ‘TB’, ‘PB’, ‘EB’, ‘ZB’, ‘YB’);
    for ($i=0; $size > 1024 && $i < count($sizes) - 1; $i++) $size /= 1024;
    return round($size,$round).$sizes[$i];
}

Usage:

formatSize(‘12345′);

*********** UPDATE **********
From LogicEarth at Sitepoint, an alternative method
Cheers LE :)

function fromBytes ( $size, $place = 3, $iec = true, $bits = false )
{
        $messure = ‘KMGTPXZY’;
        $factor  = $iec ? 1024 : 1000;
        $count   = 0;

        if ($bits) { $size *= 8; }

        while ( $size >= $factor ) {
                $size /= $factor; $count++;
        }

        $messure = $count ? $messure[$count ] . ( $iec ? ‘i’ : ) : ;
        $messure = !$bits ? $messure . ‘B’ : strtolower( $messure ) . ‘b’;

        return round( $size, $place ) . ‘ ‘ . $messure;
}

2 Responses

  1. ggg Says:

    Good site..keep up the work

  2. Logic Says:

    Thought you might like another byte formatting function :)

    But not sure how to do code here, so pastebin ^^;

    http://pastebin.com/f7644dd4d

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.