Home > Backend Development > PHP Tutorial > A brief introduction to PHP's method of converting bytes into KB, MB, GB, and TB

A brief introduction to PHP's method of converting bytes into KB, MB, GB, and TB

巴扎黑
Release: 2023-03-15 17:06:02
Original
2950 people have browsed it

This article mainly introduces PHP's method of converting Byte into KB, MB, GB, and TB. It analyzes the specific implementation method of PHP's conversion operation for Byte in the form of examples, involving PHP mathematical operations. For the use of the function, friends who need it can refer to

This article describes the method of converting the number of bytes into KB, MB, GB, and TB in PHP. Share it with everyone for your reference, the details are as follows:

The method of converting Byte into KB, MB, GB, and TB in Java was introduced earlier. Here, PHP is used to implement this function. The code is very simple:


<?php
function getFilesize($num){
   $p = 0;
   $format=&#39;bytes&#39;;
   if($num>0 && $num<1024){
     $p = 0;
     return number_format($num).&#39; &#39;.$format;
   }
   if($num>=1024 && $num<pow(1024, 2)){
     $p = 1;
     $format = &#39;KB&#39;;
  }
  if ($num>=pow(1024, 2) && $num<pow(1024, 3)) {
    $p = 2;
    $format = &#39;MB&#39;;
  }
  if ($num>=pow(1024, 3) && $num<pow(1024, 4)) {
    $p = 3;
    $format = &#39;GB&#39;;
  }
  if ($num>=pow(1024, 4) && $num<pow(1024, 5)) {
    $p = 3;
    $format = &#39;TB&#39;;
  }
  $num /= pow(1024, $p);
  return number_format($num, 3).&#39; &#39;.$format;
}
echo "来自脚本之家www.jb51.net的测试结果:<br/>";
echo getFilesize(200)."<br/>";
echo getFilesize(20000)."<br/>";
echo getFilesize(2000000)."<br/>";
echo getFilesize(200000000)."<br/>";
echo getFilesize(20000000000)."<br/>";
echo getFilesize(2000000000000)."<br/>";
?>
Copy after login

The running result is as follows:

The above is the detailed content of A brief introduction to PHP's method of converting bytes into KB, MB, GB, and TB. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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