note 55732 added to function.filesize

From: Date: Thu, 11 Aug 2005 21:31:15 +0000
Subject: note 55732 added to function.filesize
Groups: php.notes 
Request: Send a blank email to php-notes+get-93464@lists.php.net to get a copy of this message
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]; } ?> ---- Manual Page -- http://www.php.net/manual/en/function.filesize.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+55732 Delete: added to the manual -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes&reason=added+to+the+manual Delete: bad code -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes&reason=bad+code Delete: spam -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes&reason=spam Delete: useless -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes&reason=useless Delete: non-english -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes&reason=non-english Delete: other reasons -- http://master.php.net/manage/user-notes.php?action=delete+55732&report=yes Reject -- http://master.php.net/manage/user-notes.php?action=reject+55732&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#93464) next »