Skip to content

Instantly share code, notes, and snippets.

@kernusr
Last active July 29, 2022 07:22
Show Gist options
  • Save kernusr/a9ce714db4e2ff51c864bb951f14e7f3 to your computer and use it in GitHub Desktop.
Save kernusr/a9ce714db4e2ff51c864bb951f14e7f3 to your computer and use it in GitHub Desktop.
Преобразует байты в удобно читаемый формат (KB, MB, UB и т.д.)
<?php
/**
* @param int $bytes Число байт
* @param int $decimals Число знаков после запятой в ответе
*
* @return string Перобразованная в удобно читаемый формат строка
*/
function formatBytes(int $bytes, int $decimals = 2)
{
if ($bytes === 0)
{
return '0 Bytes';
}
$k = 1024;
$dm = max($decimals, 0);
$sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
$i = floor(log($bytes) / log($k));
return number_format((double) ($bytes / pow($k, $i)), $dm) . ' ' . $sizes[$i];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment