Created
November 20, 2014 15:38
-
-
Save csanquer/f66339c6c1b15ec0c838 to your computer and use it in GitHub Desktop.
Format bytes to best unit
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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