Depending on the number of bytes selects the maximum allowable value.

function bytesConverting($bytes) { $s = ['байт', 'Кбайт', 'Мбайт', 'Гбайт', 'Тбайт', 'Пбайт']; $e = floor(log($bytes)/log(1024)); return sprintf('%.2f ' . $s[$e], ($bytes/pow(1024, floor($e)))); } 

How are things from the point of view of algebra? Is it possible to simplify \ change \ have a better option?

  • one
    There is no limit on the upper limit, 1024 petabytes will fall into error. Where to simplify - I do not know. - etki
  • one
    The substring "byte" is repeated in each value. - Sergiks

1 answer 1

A few notes:

  1. "Petabyte" or "PB" and other prefixes given in question refer to powers of 10 , not 2. Therefore, divide by 1000, not 1024;
  2. you take the natural logarithm with the php log() operator (based on e ), but you probably need to base 10: log($bytes, 10) ;
  3. as rightly noted by @Etki , there are no cases of going beyond the expected values ​​- both down and down (and even they will send a string by mistake);
  4. the prefix "byte" is present in all variants - why not remove it from the array ["", "К", "М", ..] , and attribute it once to the result?
  5. not tested, but probably logarithms are considered a little longer than a simple comparison of numbers. Then the code with the cascade if .. else if for each band will be faster.