PHP Unit Converter
July 17'th 2008 03:13:08 pm
Just a little snippet I created a while back and used recently, This function takes any number of bytes and returns it formatted as the "better looking" Unit.
Usage:
string parse_size(number $size[,string $to][, bool $raw]);
Returns a string containing $size represented as $to followed by $to's suffix, if the optional value $raw is set to true returns a number.
Allowed values for $to are:
- b
- kb
- mb
- gb
- tb
- pb
Example:
parse_size(6789785445); //6.32 GigaBytes parse_size(6789785445, 'mb'); //6,475.24 MegaBytes parse_size(6789785445, 'mb', true); //6,475.24
A working example can be found here
The code:
//Parsea un numero dado en bytes a cualquier notaciÑn function parse_size($size, $to = false, $raw = false){ $octal = true; 'name' => "Byte", 'depth' => 0 ), 'name' => "KiloByte", 'depth' => 1 ), 'name' => "MegaByte", 'depth' => 2 ), 'name' => "GigaByte", 'depth' => 3 ), 'name' => "TeraByte", 'depth' => 4 ), 'name' => "PetaByte", 'depth' => 5 ) ); //Utilizamos escala octal (como en el sistema) o decimal (como en los discos duros)??? $escala = ($octal)?1024:1000; if($to != false && !$units[$to]) return false; if(!$to){ $loop = true; $to = 'kb'; } if($size < $escala){ $to = 'b'; $parsed = $size; $s = ($parsed == 1)?"":"s"; } $s = ($parsed == 1)?"":"s"; if($loop){ $i = 2; while($parsed > 1 && $i < 6){ 'value' => $parsed, 'key' => $keys[$i-1] ); $to = $keys[$i]; $parsed = parse_size($size, $to, true); $i++; } if($parsed < 1){ $parsed = $previous['value']; $to = $previous['key']; } } if($raw) return $parsed; }
Just a friendly reminder. All the code I post in here is licensed under an MIT License unless explicitly stated.
Alex
Just what I was looking for.
Thanks a lot.
Post Your Comments
Your Name