Rasher's Toolbox

Back

bytes2human

string bytes2human(int bytes [, int precision]) -- Convert a number of bytes to human readable.

Description

Converts a number of bytes into a human readable format. The optional precision parameter decides the precision of the value returned. I admit to having written this way too confusing, but readability was put aside for a moment :)

Example

<?php
  
echo "125926 is " bytes2human(125926);
?>

This will output:

125926 is 122.97kB

Source

Published under the terms of the BSD License

<?php
function bytes2human($bytes$precision 2) {
    if (
abs($bytes)<1024) return $bytes."B";
    
$suffixes = array("kB","MB","GB","TB","PB","EB","ZB","YB");
    for(
$i=0,$bytes /= 1024;abs($bytes)>1024;$i++, $bytes /= 1024);
    return 
sprintf("%01.${precision}f "$bytes).$suffixes[$i];
}
?>

Last updated: Sat Jun 14 20:02:45 CEST 2008

Valid XHTML 1.0! Valid HTML 3.2!