Skip to content
GreenSnippets

Format bytes as a readable size in PHP

Convert a number of bytes to KB, MB or GB with a chosen precision.

PHP
<?php
function formatBytes(int $bytes, int $precision = 1): string
{
    if ($bytes < 0) {
        throw new InvalidArgumentException('bytes must be non-negative');
    }
    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    $power = $bytes > 0 ? min((int) floor(log($bytes, 1024)), count($units) - 1) : 0;
    $value = round($bytes / (1024 ** $power), $precision);
    return rtrim(rtrim(number_format($value, $precision, '.', ''), '0'), '.') . ' ' . $units[$power];
}

Example / expected output

Output
formatBytes(1536);      // "1.5 KB"
formatBytes(5000000);   // "4.8 MB"

How it works

Base-1024 steps with trailing zeros removed. max and min keep the unit index inside the array so extremely large or zero values do not cause warnings.