Home > Article > Backend Development > PHP format byte size
How to format byte size in PHP.
/** * 格式化字节大小 * @param number $size 字节数 * @param string $delimiter 数字和单位分隔符 * @return string 格式化后的带单位的大小 */ function get_byte($size, $delimiter = '') { $units = array('B', 'KB', 'MB', 'GB', 'TB', 'PB'); for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024; return round($size, 2) . $delimiter . $units[$i]; }
Usage:
$size = '5454646'; echo get_byte($size);
Output:
5.2MB
Explanation:
Parameters $size is passed in the number of bytes, and the unit is kb through the method get_byte. Convert bytes to MB and back.