size_format()
Convert number of bytes largest unit bytes will fit into.
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 YB 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.
Uses: number_format_i18n()
1 time — 0.000025 sec (very fast) | 50000 times — 0.11 sec (very fast) | PHP 7.0.8, WP 4.6
No Hooks.
Return
String|false
. Number string on success, false on failure.
Usage
size_format( $bytes, $decimals );
- $bytes(int|string) (required)
- Number of bytes. Note max integer size for integers.
- $decimals(int)
- Precision of number of decimal places.
Examples
#1 Byte conversion demonstration
echo size_format( 99 ); //> 99 B echo size_format( 9999 ); //> 10 KB echo size_format( '9999' ); //> 10 KB echo size_format( 9999, 2 ); //> 9,76 KB echo size_format( 9999999 ); //> 10 MB echo size_format( 9999999999 ); //> 9 GB echo size_format( 9999999999999 ); //> 9 TB
#2 Display the size of a file in human-readable format
$file_size = 1229; // filesize in bytes echo size_format( $file_size, $decimals = 2 ); // 1.20 KB
Changelog
Since 2.3.0 | Introduced. |
Since 6.0.0 | Support for PB, EB, ZB, and YB was added. |