Last active
January 16, 2018 22:08
-
-
Save juanparati/377dfe5edca7e9c2d4ea013d7a413da5 to your computer and use it in GitHub Desktop.
Convert human readable memory size Like a Pro™️
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 | |
function convertMemorySize($strval, string $to_unit = 'b') | |
{ | |
$strval = strtolower(str_replace(' ', '', $strval)); | |
$val = floatval($strval); | |
$to_unit = strtolower(trim($to_unit))[0]; | |
$from_unit = str_replace($val, '', $strval); | |
$from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0]; | |
$units = 'kmgtph'; // (k)ilobyte, (m)egabyte, (g)igabyte and so on... | |
// Convert to bytes | |
if ($from_unit !== 'b') | |
$val *= 1024 ** (strpos($units, $from_unit) + 1); | |
// Convert to unit | |
if ($to_unit !== 'b') | |
$val /= 1024 ** (strpos($units, $to_unit) + 1); | |
return $val; | |
} | |
convertMemorySize('1024Kb', 'Mb'); // 1 | |
convertMemorySize('1024', 'k') // 1 | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment