Learning never exhausts the mind

By

This function will format a given number into a pretty file size, for example, convert 1000000 to 1MB, 3523 to 3k and so on.
function formatbytes($val, $digits = 3, $mode = "SI", $bB = "B")
{ 
  $si = array("", "k", "M", "G", "T", "P", "E", "Z", "Y");
  $iec = array("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi");

  switch(strtoupper($mode)) 
  {
      case "SI" : $factor = 1000; $symbols = $si; break;
      case "IEC" : $factor = 1024; $symbols = $iec; break;
      default : $factor = 1000; $symbols = $si; break;
  }

  switch($bB) 
  {
      case "b" : $val *= 8; break;
      default : $bB = "B"; break;
  }
  
  for($i=0;$i<count($symbols)-1 && $val>=$factor;$i++)
      $val /= $factor;
  
  $p = strpos($val, ".");
  if($p !== false && $p > $digits) 
    $val = round($val);
  elseif($p !== false) 
    $val = round($val, $digits-$p);
  
  return round($val, $digits) . " " . $symbols[$i] . $bB;
}

Simply pass in an integer file size and it will return a value to 3 significant figures using SI notation. You can increase the number of figures by changing the second parameter in the call and the mode in the last two.

Examples:
$filename = 'somefile.txt';
echo $filename . ': ' . filesize($filename) . ' bytes';

Will output "somefile.txt: 219543 bytes"

$filename = 'somefile.txt';
echo $filename . ': ' . formatbytes(filesize($filename));

Will output "somefile.txt: 219 kB"

I did not write this function, but I have been using it for years. I do not know who the original author is, but if you know please let me know so I can give credit.

I also have a similar function for ASP.Net and C# which pretty formats file size.

 

Sharing is caring!

If you enjoyed this post, please share it with others. Click one of the social media buttons below to share on Facebook, Twitter, LinkedIn, Pinterest or email to a friend.

Leave a Reply

Fields marked with * are mandatory.

We respect your privacy, and will not make your email public. Hashed email address may be checked against Gravatar service to retrieve avatars. This site uses Akismet to reduce spam. Learn how your comment data is processed.