|
Posted by Kimmo Laine on 12/20/05 15:37
"Prince of Code" <princeofcode@gmail.com> wrote in message
news:1135084052.220659.211190@g49g2000cwa.googlegroups.com...
> Hey all,
> I am writing a function that converts given bytes into KB , MB
> or GB. This function will work as in Windows if the file size is too
> large in MB it will show as 2.34 MB instead 23400 KB( for example )
>
> I find still it can be optimized. Ideas welcome
>
> /*
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> Function : byteConversion( $byte )
> Description : This functions converts given bytes into human
> readable format.
> Params : raw bytes
> return : byte in Readable format 5.23 MB 220 KB
> Version : 1.0
> ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
> */
>
> function byteConversion( $byte ){
>
> $result = 0;
>
> // becoz 1 KB = 1024 Bytes
> if( $byte <= 1023 ){
> $result = round($byte,2)."Byte(s)";
> // becoz 1 MB = 1024 KB = 1024 * 1024
> }elseif( $byte <= 1048575 ){
> $byte = $byte / 1024 ;
> $result = round($byte,2)." KB ";
> // becoz 1 GB = 1024 MB = 1024 * 1024 * 1024
> }elseif( $byte <= 1073741823 ){
> $byte = $byte / 1048576 ;
> $result = round($byte,2)." MB ";
> // becoz 1 TB = 1024 GB = 1024 * 1024 * 1024 * 1024
> }elseif( $byte <= 1099511627775 ){
> $byte = $byte / 1073741824 ;
> $result = round($byte,2)." GB ";
> }
>
> return $result;
> }
clearly it can be done with a loop structure:
function byteConversion($bytes){
$sizes = array('byte(s)', 'KB', 'MB', 'GB', 'TB');
for($multiples=0, $result=$bytes; $result>=1024; $multiples++,
$result/=1024);
return number_format($result,2).' '.$sizes[$multiples];
}
//examples of usage:
echo byteConversion(8192);
echo '<br/>';
echo byteConversion(1024);
echo '<br/>';
echo byteConversion(filesize(__FILE__));
echo '<br/>';
echo byteConversion(4700000000);
echo '<br/>';
echo byteConversion(1440000);
--
"En ole paha ihminen, mutta omenat ovat elinkeinoni." -Perttu Sirviφ
antaatulla.sikanautaa@gmail.com.NOSPAM.invalid
[Back to original message]
|