Question

some thing like that

function convert_size($from,$to,$unit){

some code...

return $calculated_value

}

echo convert_size("YB","KB",50);
  • Byte (B)
  • Kilobyte (KB)
  • Megabyte (MB)
  • Gigabyte (GB)
  • Terabyte (TB)
  • Petabyte (PB)
  • Exabyte (EB)
  • Zettabyte (ZB)
  • Yottabyte (YB)
Was it helpful?

Solution 2

How about that:

function convert_size($from,$to,$unit){
  $units = array('B', 'KB', 'MB', 'GB', 'TB','PB','EB','ZB','YB');
  if(($fromPosition = array_search($from,$units)) === false){
     return false;
  }
  if(($toPosition = array_search($to,$units)) === false){
    return false;
  }
  $diffUnits = $fromPosition-$toPosition;
  return $unit * (pow(1024, $diffUnits));
}

OTHER TIPS

for a more clean way to do this, use this function:

function convert_size($from, $to, $unit)
{
    $units = array(
        'B' => 1,
        'KB' => 1024,
        'MB' => 1024^2,
        'GB' => 1024^3,
        // fill with more units you need
    );

    return ($unit*$units[$from])/$units[$to];
}

for example to convert 3Gb to MB, the final formula should be (3×(1024^3))÷(1024^2), and it will result in 3072MB.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top