note 100097 deleted from function.filesize by aharvey
| From: | aharvey@php.net | Date: | Tue, 22 Jan 2013 00:18:13 +0000 |
| Subject: | note 100097 deleted from function.filesize by aharvey | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-193314@lists.php.net to get a copy of this message | ||
Note Submitter: joaoptm78 at gmail dot com
----
And this is my short and very clever simple function. Faster than some of the examples below.
<?php
function format_bytes($size) {
$units = array(' B', ' KB', ' MB', ' GB', '
TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
return round($size, 2).$units[$i];
}
?>
You can add more units to the $units array and change the number 4 in "$i < 4"
accordingly.
But if you want it really fast try this not-so-neat function:
<?php
function format_bytes($bytes) {
if ($bytes < 1024) return $bytes.' B';
elseif ($bytes < 1048576) return round($bytes / 1024, 2).' KB';
elseif ($bytes < 1073741824) return round($bytes / 1048576, 2).' MB';
elseif ($bytes < 1099511627776) return round($bytes / 1073741824, 2).' GB';
else return round($bytes / 1099511627776, 2).' TB';
}
?>
I guess you can do it in 1000 different ways :)