size_format

Convert number of bytes largest unit bytes will fit into.

Description

(string|false) size_format( (int|string) $bytes, (int) $decimals = 0 ); 

It is easier to read 1 KB than 1024 bytes and 1 MB than 1048576 bytes. Converts number of bytes to human readable number by taking the number of that unit that the bytes will go into it. Supports TB value.

Please note that integers in PHP are limited to 32 bits, unless they are on 64 bit architecture, then they have 64 bit size. If you need to place the larger size then what PHP integer type will hold, then use a string. It will be converted to a double, which should always have 64 bit length.

Technically the correct unit names for powers of 1024 are KiB, MiB etc.

Returns (string|false)

False on failure. Number string on success.

Parameters (2)

0. $bytes (int|string)
Number of bytes. Note max integer size for integers.
1. $decimals — Optional. (int)
Precision of number of decimal places. Default 0.

Usage

  1. if ( !function_exists( 'size_format' ) ) { 
  2. require_once ABSPATH . WPINC . '/functions.php'; 
  3.  
  4. // Number of bytes. Note max integer size for integers. 
  5. $bytes = null; 
  6.  
  7. // Optional. Precision of number of decimal places. Default 0. 
  8. $decimals = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = size_format($bytes, $decimals); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/functions.php  
  1. function size_format( $bytes, $decimals = 0 ) { 
  2. $quant = array( 
  3. 'TB' => TB_IN_BYTES,  
  4. 'GB' => GB_IN_BYTES,  
  5. 'MB' => MB_IN_BYTES,  
  6. 'KB' => KB_IN_BYTES,  
  7. 'B' => 1,  
  8. ); 
  9.  
  10. if ( 0 === $bytes ) { 
  11. return number_format_i18n( 0, $decimals ) . ' B'; 
  12.  
  13. foreach ( $quant as $unit => $mag ) { 
  14. if ( doubleval( $bytes ) >= $mag ) { 
  15. return number_format_i18n( $bytes / $mag, $decimals ) . ' ' . $unit; 
  16.  
  17. return false;