• May 7, 2024
  • Chiwetara Igwe
  • 0

In PHP, you can convert bytes into kilobytes (KB), megabytes (MB), and gigabytes (GB) by dividing the given number of bytes by the corresponding factor.

In this example, I will show you how to convert bytes to kb mb gb in php

<?PHP
    
function formatBytes($bytes, $precision = 2) {
    $kilobyte = 1024;
    $megabyte = $kilobyte * 1024;
    $gigabyte = $megabyte * 1024;
    
    if ($bytes < $kilobyte) {
        return $bytes . ' B';
    } elseif ($bytes < $megabyte) {
        return round($bytes / $kilobyte, $precision) . ' KB';
    } elseif ($bytes < $gigabyte) {
        return round($bytes / $megabyte, $precision) . ' MB';
    } else {
        return round($bytes / $gigabyte, $precision) . ' GB';
    }
}
    
/* Example usage: */
$bytes = 567890123; /* Replace this with the actual number of bytes you have */
  
echo formatBytes($bytes);
  
?>
Tags:

Chiwetara Igwe

I'm a full-stack developer, entrepreneur and owner of techbly.ng. I live in Nigeria and I love to write tutorials and tips that can help to other web developers. I am experienced in PHP, Laravel, Angular, Vue, Node, Javascript, JQuery, Codeigniter and Bootstrap. I am passionate about learning new things and keeping up with the latest trends and technologies.

http://techbly.ng

Leave a Reply

Your email address will not be published. Required fields are marked *

× Have a question?