Skip to content

Instantly share code, notes, and snippets.

@Programie
Created November 25, 2014 23:18
Show Gist options
  • Select an option

  • Save Programie/f64c0937fe257b3fb1f6 to your computer and use it in GitHub Desktop.

Select an option

Save Programie/f64c0937fe257b3fb1f6 to your computer and use it in GitHub Desktop.
Format bytes into a human readable format
<?php
/**
* Format the given file size in bytes to a human readable format.
*
* @param int $size The file size to format in bytes
* @param int $precision The optional number of decimal digits to round to
* @return string The formatted file size (e.g. "4.7G")
*/
function formatFileSize($size, $precision = 1)
{
$units = array("B", "K", "M", "G", "T", "P", "E", "Z", "Y");
$useUnit = null;
foreach ($units as $index => $unit)
{
if ($size < 1024)
{
$useUnit = $unit;
break;
}
$size /= 1024;
}
if ($useUnit == null)
{
$useUnit = end($units);
}
return round($size, $precision) . $useUnit;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment