PHP format byte size

高洛峰
Release: 2016-10-20 15:28:25
Original
1321 people have browsed it

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];
}
Copy after login


Usage:

$size = &#39;5454646&#39;;
echo get_byte($size);
Copy after login

Output:

5.2MB
Copy after login

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.


Related labels:
php
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!