format_size

Definition

format_size($size, $langcode = NULL)
includes/common.inc, line 1131

Description

Generate a string representation for the given byte count.

Parameters

$size A size in bytes.

$langcode Optional language code to translate to a language other than what is used to display the page.

Return value

A translated string representation of the size.

Related topics

Namesort iconDescription
FormattingFunctions to format numbers, strings, dates, etc.

Code

<?php
function format_size($size, $langcode = NULL) {
  if ($size < 1000) {
    return format_plural($size, '1 byte', '@count bytes', array(), $langcode);
  }
  else {
    $size = $size / 1000; // convert bytes to kilobytes (1000 bytes)
    $units = array(
      t('@size KB', array(), $langcode),
      t('@size MB', array(), $langcode),
      t('@size GB', array(), $langcode),
      t('@size TB', array(), $langcode),
      t('@size PB', array(), $langcode),
      t('@size EB', array(), $langcode),
      t('@size ZB', array(), $langcode),
      t('@size YB', array(), $langcode),
    );
    foreach ($units as $unit) {
      if (round($size, 2) >= 1000) {
        $size = $size / 1000;
      }
      else {
        break;
      }
    }
    return str_replace('@size', round($size, 2), $unit);
  }
}
?>
 
 

All source code and documentation on this site is released under the terms of the GNU General Public License, version 2 and later. Drupal is a registered trademark of Dries Buytaert.