Home  >  Article  >  Backend Development  >  PHP format byte size

PHP format byte size

高洛峰
高洛峰Original
2016-10-20 15:28:251335browse

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 = &#39;5454646&#39;;
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.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn