A small immutable PHP value object for byte-size conversion and formatting.
ByteSize provides a clean API for converting, formatting, and displaying byte-based values in PHP applications.
ByteSize helps you:
- create a size from bytes, KB, MB, GB, or TB
- convert the value to any supported unit
- format values for UI and logs
- generate human-readable output
- immutable and predictable value object
- explicit decimal unit conversion
- clean formatting API with customizable labels
- useful for file sizes, storage usage, logs, CLI output, and UI rendering
The library uses decimal units:
1 KB = 1000 B1 MB = 1000 KB1 GB = 1000 MB1 TB = 1000 GB
composer require elephant-php/byte-size- PHP
8.1or higher
use ElephantPhp\ByteSize\ByteSize;
$size = ByteSize::fromBytes(2_500_000);
echo $size->toBytes(); // 2500000
echo $size->toKilobytes(); // 2500
echo $size->toMegabytes(); // 2.5
echo $size->toGigabytes(); // 0.0025
echo $size->toTerabytes(); // 0.0000025use ElephantPhp\ByteSize\ByteSize;
ByteSize::fromBytes(2500000);
ByteSize::fromKilobytes(2500);
ByteSize::fromMegabytes(2.5);
ByteSize::fromGigabytes(0.0025);
ByteSize::fromTerabytes(0.0000025);use ElephantPhp\ByteSize\ByteSize;
$size = ByteSize::fromBytes(2_500_000);
$size->toBytes(); // 2500000
$size->toKilobytes(); // 2500
$size->toMegabytes(); // 2.5
$size->toGigabytes(); // 0.0025
$size->toTerabytes(); // 0.0000025Use format() when you want an explicit unit.
use ElephantPhp\ByteSize\ByteSize;
use ElephantPhp\ByteSize\ByteSizeUnit;
$size = ByteSize::fromBytes(2_500_000);
echo $size->format(ByteSizeUnit::TERABYTES, 7); // 0.0000025 TB
echo $size->format(ByteSizeUnit::TERABYTES, 7, ''); // 0.0000025
echo $size->format(ByteSizeUnit::MEGABYTES, 2); // 2.5 MB
echo $size->format(ByteSizeUnit::MEGABYTES, 2, 'МБ'); // 2.5 МБ
echo $size->format(ByteSizeUnit::MEGABYTES, 2, 'MBs'); // 2.5 MBsArguments:
$unitis the unit you want to format to$precisionis the maximum number of decimal places before trimming trailing zeros$labeloverrides the default unit label
Label behavior:
nulluses the default label fromByteSizeUnit''returns only the numeric value- any other string is used as a custom label
Use human() when you want the library to choose the most suitable unit automatically.
use ElephantPhp\ByteSize\ByteSize;
$size = ByteSize::fromBytes(2_500_000);
echo $size->human(); // 2.5 MB
echo $size->human('МБ'); // 2.5 МБ
echo (string) $size; // 2.5 MBExamples of automatic unit switching:
ByteSize::fromBytes(999)->human(); // 999 B
ByteSize::fromBytes(1000)->human(); // 1 KB
ByteSize::fromBytes(1000000)->human(); // 1 MB
ByteSize::fromBytes(1000000000)->human(); // 1 GB
ByteSize::fromBytes(1000000000000)->human(); // 1 TBuse ElephantPhp\ByteSize\ByteSizeUnit;
ByteSizeUnit::BYTES;
ByteSizeUnit::KILOBYTES;
ByteSizeUnit::MEGABYTES;
ByteSizeUnit::GIGABYTES;
ByteSizeUnit::TERABYTES;vendor/bin/testo runMIT License
Please see LICENSE for more information.