PHP Unit Converter

JParra 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:

  1. 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:

  1. parse_size(6789785445);
  2. //6.32 GigaBytes
  3.  
  4. parse_size(6789785445, 'mb');
  5. //6,475.24 MegaBytes
  6.  
  7. parse_size(6789785445, 'mb', true);
  8. //6,475.24

A working example can be found here

The code:

  1. //Parsea un numero dado en bytes a cualquier notaci—n
  2. function parse_size($size, $to = false, $raw = false){
  3. $octal = true;
  4.  
  5. $units = array(
  6. 'b' => array(
  7. 'name' => "Byte",
  8. 'depth' => 0
  9. ),
  10. 'kb' => array(
  11. 'name' => "KiloByte",
  12. 'depth' => 1
  13. ),
  14. 'mb' => array(
  15. 'name' => "MegaByte",
  16. 'depth' => 2
  17. ),
  18. 'gb' => array(
  19. 'name' => "GigaByte",
  20. 'depth' => 3
  21. ),
  22. 'tb' => array(
  23. 'name' => "TeraByte",
  24. 'depth' => 4
  25. ),
  26. 'pb' => array(
  27. 'name' => "PetaByte",
  28. 'depth' => 5
  29. )
  30. );
  31. //Utilizamos escala octal (como en el sistema) o decimal (como en los discos duros)???
  32. $escala = ($octal)?1024:1000;
  33.  
  34. if($to != false && !$units[$to]) return false;
  35. if(!$to){
  36. $loop = true;
  37. $to = 'kb';
  38. }
  39. if($size < $escala){
  40. $to = 'b';
  41. $parsed = $size;
  42. $s = ($parsed == 1)?"":"s";
  43. return number_format($parsed, 2)." {$units[$to]['name']}$s";
  44. }
  45. $ss = pow($escala, $units[$to]['depth']);
  46. $parsed = round($size/$ss, 2);
  47. $s = ($parsed == 1)?"":"s";
  48. if($loop){
  49. $keys = array_keys($units);
  50. $i = 2;
  51. while($parsed > 1 && $i < 6){
  52. $previous = array(
  53. 'value' => $parsed,
  54. 'key' => $keys[$i-1]
  55. );
  56. $to = $keys[$i];
  57. $parsed = parse_size($size, $to, true);
  58. $i++;
  59. }
  60. if($parsed < 1){
  61. $parsed = $previous['value'];
  62. $to = $previous['key'];
  63. }
  64. }
  65. if($raw) return $parsed;
  66. return number_format($parsed, 2)." {$units[$to]['name']}$s";
  67. }

Just a friendly reminder. All the code I post in here is licensed under an MIT License unless explicitly stated.

1 Comments Permalink Tags: php, snippet

Alex

October82008|21:42

Just what I was looking for.
Thanks a lot.

Post Your Comments

Your Name