Generate Readable Byte Labels Using PHP

By  on  

Whenever you manage disk space, it's infinitely easier to read when when the bytes are displayed in KB, MB, GB... format. When reading files on the disk, the server returns the disk space in bytes so it's on us programmers to program file sizes for display. Using PHP, this task is cake.

function format_bytes($bytes)
{
    $labels = array('B','KB','MB','GB','TB');
    for($x = 0; $bytes >= 1024 && $x < (count($labels) - 1); $bytes /= 1024, $x++);
    return(round($bytes, 2).' '.$labels[$x]);
}

Users will appreciate this!

Recent Features

  • By
    5 Awesome New Mozilla Technologies You&#8217;ve Never Heard Of

    My trip to Mozilla Summit 2013 was incredible.  I've spent so much time focusing on my project that I had lost sight of all of the great work Mozillians were putting out.  MozSummit provided the perfect reminder of how brilliant my colleagues are and how much...

  • By
    CSS Filters

    CSS filter support recently landed within WebKit nightlies. CSS filters provide a method for modifying the rendering of a basic DOM element, image, or video. CSS filters allow for blurring, warping, and modifying the color intensity of elements. Let's have...

Incredible Demos

  • By
    CSS Text Overlap

    One of the important functions of CSS is to position elements. Margin, padding, top, left, right, bottom, position, and z-index are just a few of the major players in CSS positioning. By using the above spacing...

  • By
    Create Custom Events in MooTools 1.2

    Javascript has a number of native events like "mouseover," "mouseout", "click", and so on. What if you want to create your own events though? Creating events using MooTools is as easy as it gets. The MooTools JavaScript What's great about creating custom events in MooTools is...

Discussion

  1. JP

    I always like using the right-shift operator for this kind of stuff. So instead of:

    $bytes /= 1024

    I would use:

    $bytes >>= 10

    Of course, you lost the digits after the decimal point (unless you get fancy), but on the plus side, it’s way faster than floating point division. The shift operators must be some of the loneliest operators in PHP, don’t you think?

  2. Nice one!
    I did a similar function … somewhat overkill, but a usefull thing over the years =)
    http://openminds.lucido-media.de/human-readable-bytes-sorry-php-net

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!