note 55732 deleted from function.filesize by aidan

From: Date: Wed, 09 Nov 2005 06:14:43 +0000
Subject: note 55732 deleted from function.filesize by aidan
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-98297@lists.php.net to get a copy of this message
Note Submitter: anommander dot rake at gmail dot com ---- A few proposals regarding the formatting of the output of the filesize function (i.e. 1024 -> 1 KB etc. ). First, it bodes well to remember what it actually means: *drum roll* a logarithm. Here a little working example, not actually intended for real use <? function filesize_format_alt ($bytes) { $names = array( 'B', 'KB', 'MB', 'GB', 'TB'); $i = floor(log($bytes)/log(1024)); //log_1024($bytes) return number_format(round($bytes/pow(1024,$i))).' '.$names[$i]; } ?> or, a little more realistic: <? function filesize_format_alt2 ($bytes) { if ( 0 > $bytes) { return $bytes; } $names = array( 'B', 'KB', 'MB', 'GB', 'TB'); $values = array( 0, 1024, 1048576, 1073741824, 1099511627776); $i = floor(log($bytes)/6.9314718055994530941723212145818); //log(1024) = 6.9314718055994530941723212145818 return number_format(round($bytes/$values[$i])).' '.$names[$i]; } ?> The advantage of using the logarithm, is the absence of any loops; the downside is that the logarithm is a rather costly operation. Also, it is far clearer, what actually gets done. As most files will be in the KB range however, a loop might be a better approach (again, not code intended for real use): <? function filesize_format ($bytes) { if ( 0 > $bytes) { return $bytes; } $names = array( 'B', 'KB', 'MB', 'GB', 'TB'); $i = 0; $count = count($names) ; while (i < $count && $bytes > 1024) //We expect this to terminate after two to three iterations. { $bytes = $bytes/1024; $i++; } return number_format($bytes).' '.$names[$i]; } ?>

« previous php.notes (#98297) next »