PHP code example of unit / information

1. Go to this page and download the library: Download unit/information library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

unit / information example snippets


use Unit\Information\Size;

// Format 1 Byte
(new Size(1))->format(); // "1B"

// Format Byte values
(new Size(4300000))->format();     // "4.3MB"
(new Size(73042346800))->format(); // "73.0423468GB"

// Cut at precision
(new Size(73042346800))->format(null);    // "73GB"
(new Size(73042346800))->format(null, 0); // "73GB"
(new Size(73042346800))->format(null, 2); // "73.04GB"

// Custom format
(new Size(73042346800))->format(null, 1, '%size% %unit_abbreviation% (%unit_name%)'); // "73.0 GB (Gigabyte)"

use Unit\Information\Size;
use Unit\Information\Unit;

(new Size(73042346800))->format(Unit::MEGABYTE); // "73042MB"
(new Size(300000))->format(Unit::MEGABYTE, 1);   // "0.3MB"

use Unit\Information\Size;
use Unit\Information\Unit;

(new Size(100000))->get(Unit::KILOBYTE); // 100
(new Size(1))->get(Unit::KILOBYTE);      // 0.001

use Unit\Information\Size;

new Size(1);     // If the value is not a string it is treated as a Byte value which is transformed to a Bit value internally
new Size('1MB'); // If it is a string the string is transformed to a Bit value intelligently
new Size('0.05GB');

use Unit\Information\Size;

$size = new Size(1);
$otherSize = new Size('1MB');

$size->add($otherSize);
$size->subtract($otherSize);
$size->multiply($otherSize);
$size->divide($otherSize);

$size->add($otherSize)->subtract($otherSize); // Can be chained

use Unit\Information\Size;
use Unit\Information\InvalidPhpShorthandValueException;

$size = Size::createFromPhpShorthandValue('1M'); // Results in 1048576 Bytes
try {
    $size = Size::createFromPhpShorthandValue(ini_get('memory_limit'));
} catch (InvalidPhpShorthandValueException $exception) {
    // $exception->getMessage() is: 'The PHP shorthand value "-1" cannot be converted to a meaningful size.'
}
console
user@machine:~$ make tests
// Build PHP code coverage
user@machine:~$ make code-coverage