Just found myself needing to display bytes in a human readable format. There are countless examples that use a lot of complex techniques to achieve this, but I wanted a simpler solution. This is the method that came to mind. Rather than basing my algorithm on the numeric value, it is based on the length of the bytes.

function human_filesize($bytes, $decimals = 2) { $sz = 'BKMGTP'; $factor = floor((strlen($bytes) - 1) / 3); return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor]; }

This will return the number with the appropriate initial (B for bytes, K for kilobytes, M for megabytes, etc.) appended and the numeric with the specified number of decimal digits. It’s obviously pretty straightforward, but I always like coming up with a new way to do things and this is a faster solution than probably most if not all I’ve come across.

Andrew Milsted

March 30, 2013 at 2:00 am

I really like the function, a lot more elegant that doing a loop, just had a thought your strlen function to get the $factor is base 1000 when bytes is base 1024

have you thought of:

$factor = floor(log($bytes,1024));