byte to gb php code example

Example 1: convert gb to bytes php

<?php 
  function tobytes($size, $type)
  {
    $types = array("B", "KB", "MB", "GB", "TB", "PB"); //You can add the rest if needed..
    
    if($key = array_search($type, $types))
      return $size * pow(1024, $key);
    else return "invalid type";
  }
  
  echo tobytes(15, "MB"); //15728640
  echo tobytes(2, "KB"); //2048
  echo tobytes(3, "w/e"); //invalid type 
?>

Example 2: convert byte to megabyte php

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
}

Tags:

Php Example