<?php
/**
* @param string format Sets format for size.
* Format should containt string parseable by sprintf function and contain one %F macro that will be replaced by size. Another macro is U/u. It will be replaced with used unit. U for uppercase, u - lowercase. If 'i' is present at the end of format string, size multiplier will be set to 1024 (and units be KiB, MiB and so on), otherwise multiplier is set to 1000.
* @example "%.0F Ui" 617 KiB
* @example "%.3F Ui" 617.070 KiB
* @example "%10.3F Ui" 616.85 KiB
* @example "%.3F U" 632.096 KB
*
* @param integer $bytes Size in bytes
* @param string $unit Sets default unit. Can have these values: B, KB, MG, GB, TB, PB, EB, ZB and YB
*/
function size_format($format, $bytes, $unit = null) {
$units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
$bytes = max($bytes, 0);
if ($unit !== null)
$unit = strtoupper($unit);
if (substr($format, -1) === 'i') {
$multiplier = 1024;
$format = substr($format, 0, -1);
}
else
$multiplier = 1000;
if ($unit === null || !in_array($unit, $units)) {
$pow = floor(($bytes ? log($bytes) : 0) / log($multiplier));
$pow = min($pow, count($units) - 1);
$bytes /= pow($multiplier, $pow);
$unit = $units[$pow];
} else {
$pow = array_search($unit, $units);
$bytes /= pow($multiplier, $pow);
}
if ($multiplier == 1024)
$unit = (strlen($unit) == 2) ? substr($unit, 0, 1).'iB' : $unit;
if (strpos($format, 'u') !== false)
$format = str_replace('u', strtolower($unit), $format);
else
$format = str_replace('U', $unit, $format);
return sprintf($format, $bytes);
}
var_dump(PHP_INT_MAX);
$s = '9223372036854775808';
$i = (int)$s;
var_dump($s, $i);
var_dump(size_format('%.2F Ui', $s));
var_dump(size_format('%.2F Ui', $i));
preferences:
43.3 ms | 402 KiB | 5 Q