Format bytes as a readable size in PHP
Convert a number of bytes to KB, MB or GB with a chosen precision.
- PHP
- GreenSnippets
- MIT
- Executed with PHP 8.2
<?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
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.
Related snippets
- JavaScript Tested
Format currency and numbers with Intl
Locale-aware money, percent and compact number formatting using the built-in Intl.NumberFormat.
- Python Tested
Format bytes as a human-readable size
Convert a byte count into KB, MB, GB and so on with a configurable number of decimals.
- JavaScript Tested
Format bytes as KB, MB, GB
Convert a byte count into a short human-readable size such as 1.5 MB.
- PHP Tested
Validate emails and URLs in PHP
Use filter_var to validate email addresses and http(s) URLs, with an allow-list for schemes.

