Skip to content

Instantly share code, notes, and snippets.

@csanquer
Created November 20, 2014 15:38
Show Gist options
  • Save csanquer/f66339c6c1b15ec0c838 to your computer and use it in GitHub Desktop.
Save csanquer/f66339c6c1b15ec0c838 to your computer and use it in GitHub Desktop.
Format bytes to best unit
<?php
/**
* @param int $bytes
* @param int $precision
* @param int $baseUnit 1024 or 1000
* @return array
*/
function formatBytes($bytes, $precision = 2, $baseUnit = 1024)
{
$unit = ['B','KB','MB','GB','TB','PB','EB'];
if ($baseUnit == 1000) {
$unit = array_map('strtolower', $unit);
} else {
$baseUnit = 1024;
}
$chosenUnit = floor(log($bytes, $baseUnit));
return [
'value' => round($bytes/pow($baseUnit, $chosenUnit), $precision),
'unit' => $unit[$chosenUnit],
];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment