Return to Snippet

Revision: 17069
at August 21, 2009 20:40 by kirik


Initial Code
function calculateSize($size, $sep = ' ')
{
	$unit = null;
	$units = array('B', 'KB', 'MB', 'GB', 'TB');

	for($i = 0, $c = count($units); $i < $c; $i++)
	{
		if ($size > 1024)
		{
			$size = $size / 1024;
		}
		else
		{
			$unit = $units[$i];
			break;
		}
	}

	return round($size, 2).$sep.$unit;
}
echo calculateSize(32942443); // Result: 31.42 MB
echo calculateSize(2298543567223, ''); // Result: 2.09TB

Initial URL

                                

Initial Description
This function converts file size in bytes to the larger units.
You can add bigger values like exa-, zetta-, yotta- bytes.

Initial Title
Calculate (convert) File Size

Initial Tags
file, convert

Initial Language
PHP