PHPackages                             nmarfurt/measurements - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. nmarfurt/measurements

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

nmarfurt/measurements
=====================

A PHP library for representing and converting dimensional units of measure.

v1.4.0(4y ago)17183.8k↓31.8%41MITPHPPHP ^7.2 | ^8.0CI failing

Since Jul 11Pushed 4y ago3 watchersCompare

[ Source](https://github.com/marfurt/measurements)[ Packagist](https://packagist.org/packages/nmarfurt/measurements)[ RSS](/packages/nmarfurt-measurements/feed)WikiDiscussions master Synced 2d ago

READMEChangelog (3)Dependencies (1)Versions (7)Used By (1)

Measurements &amp; Units
========================

[](#measurements--units)

[![Build Status](https://github.com/marfurt/measurements/actions/workflows/tests.yml/badge.svg?branch=master)](https://github.com/marfurt/measurements/actions/workflows/tests.yml/badge.svg?branch=master)[![Latest Stable Version](https://camo.githubusercontent.com/b4a68635cafa573077cf10e52b8ede5d654855df993697668ec0ab07964638b4/68747470733a2f2f706f7365722e707567782e6f72672f6e6d6172667572742f6d6561737572656d656e74732f762f737461626c65)](https://packagist.org/packages/nmarfurt/measurements)[![License](https://camo.githubusercontent.com/05dec8927e8ce99905b09d84d6ef3e0b0bd1871b2e023a0e10db19ec9555aa5f/68747470733a2f2f706f7365722e707567782e6f72672f6e6d6172667572742f6d6561737572656d656e74732f6c6963656e7365)](https://packagist.org/packages/nmarfurt/measurements)

About
-----

[](#about)

This is a PHP library for representing and converting dimensional units of measure. This is inspired by the [Measurement API](https://developer.apple.com/reference/foundation/nsmeasurement) in the Apple Foundation Framework.

Installation
------------

[](#installation)

The package can be installed via [Composer](https://getcomposer.org):

```
composer require nmarfurt/measurements
```

Library Classes
---------------

[](#library-classes)

### Unit

[](#unit)

`Unit` is the abstract superclass of units. Each instance of an `Unit` subclass consists of a symbol, which can be used to create string representations of `Measurement` objects.

### Dimension

[](#dimension)

`Dimension` is an abstract subclass of `Unit` that represents unit families or a dimensional unit of measure, which can be converted into different units of the same type. Each instance of an `Dimension` subclass has a converter, which is used to represent the unit in terms of the dimension's base unit provided by the `baseUnit()` method.

> The library provides concrete subclasses for many of the most common types of physical units (listed below). If you need a custom unit type to represent a custom or derived unit, you can subclass `Dimension`. If you need to represent dimensionless units, subclass `Unit` directly.

### UnitConverter

[](#unitconverter)

A `UnitConverter` describes how to convert a unit to and from the base unit of its dimension. `UnitConverterLinear` is a `UnitConverter` subclass for converting between units using a linear equation. You can define your own converters if needed.

### Measurement

[](#measurement)

A `Measurement` object represents a measured quantity, using a unit of measure and a value. The `Measurement` class provides a programmatic interface to converting measurements into different units, as well as calculating the sum or difference between two measurements.

`Measurement` objects are initialized with a `Unit` object and double value. They are immutable and cannot be changed after being created.

> The library provides specific subclasses (so called Quantities) for measurements that correspond to the provided units (see the list below).

Provided Units &amp; Quantities
-------------------------------

[](#provided-units--quantities)

The library provides concrete subclasses for many of the most common types of physical units:

Dimension SubclassDescriptionBase UnitMeasurement SubclassUnitAccelerationUnit of measure for accelerationmeters per second squared `m/s²`AccelerationUnitAngleUnit of measure for planar angle and rotationdegrees `°`AngleUnitAreaUnit of measure for areasquare meters `m²`AreaUnitConcentrationMassUnit of measure for concentration of massmilligrams per deciliter `mg/dL`ConcentrationMassUnitDispersionUnit of measure for dispersionparts per million `ppm`DispersionUnitDurationUnit of measure for durationseconds `sec`DurationUnitElectricChargeUnit of measure for electric chargecoulombs `C`ElectricChargeUnitElectricCurrentUnit of measure for electric currentamperes `A`ElectricCurrentUnitElectricPotentialDifferenceUnit of measure for electric potential differencevolts `V`ElectricPotentialDifferenceUnitElectricResistanceUnit of measure for electric resistanceohms `Ω`ElectricResistanceUnitEnergyUnit of measure for energyjoules `J`EnergyUnitFrequencyUnit of measure for frequencyhertz `Hz`FrequencyUnitFuelEfficiencyUnit of measure for fuel consumptionliters per 100 kilometers `L/100km`FuelEfficiencyUnitIlluminanceUnit of measure for illuminancelux `lx`IlluminanceUnitLengthUnit of measure for lengthmeters `m`LengthUnitMassUnit of measure for masskilograms `kg`MassUnitPowerUnit of measure for powerwatts `W`PowerUnitPressureUnit of measure for pressurenewtons per square meter `N/m²`PressureUnitRadioactivityUnit of measure for radioactivitybecquerel `Bq`RadioactivityUnitSpeedUnit of measure for speedmeters per second `m/s`SpeedUnitTemperatureUnit of measure for temperaturekelvin `K`TemperatureUnitVolumeUnit of measure for volumeliters `L`VolumeUsage
-----

[](#usage)

### Using Measurements

[](#using-measurements)

You can define measurements as follows:

```
use Measurements\Measurement;
use Measurements\Units\UnitLength;
use Measurements\Units\UnitDuration;

$length = new Measurement(4.48, UnitLength::meters());
echo $length; // = 4.48 m

$duration = new Measurement(1.5, UnitDuration::hours());
echo $duration; // = 1.5 hr
```

You may want to enforce the unit type of a measurement by using the provided measurement subclasses (*aka* *Quantities*):

```
use Measurements\Units\UnitLength;
use Measurements\Units\UnitDuration;
use Measurements\Quantities\Length;
use Measurements\Quantities\Duration;

$length = new Length(4.48, UnitLength::meters());
echo $length; // = 4.48 m

$duration = new Duration(1.5, UnitDuration::hours());
echo $duration; // = 1.5 hr

$invalid = new Length(4.48, UnitDuration::hours()); // Will throw a UnitException exception
```

The *Quantities* objects also provide the benefit of an expressive syntax to create measurements. They make use of the `__callStatic()` magic-method to create a new instance by resolving the derived dimension.

```
use Measurements\Quantities\Length;
use Measurements\Quantities\Duration;

$length = Length::meters(4.48);
echo $length; // = 4.48 m

$duration = Duration::hours(1.5);
echo $duration; // = 1.5 hr

$invalid = Length::hours(4.48); // Will throw a BadMethodCallException exception
```

Some of the *Measurement* subclasses expose convenience methods to easily create instances from other measurements.

```
use Measurements\Quantities\Length;
use Measurements\Quantities\Duration;

$distance = Length::kilometers(18);
$time = Duration::hours(1);

$speed = Speed::fromLengthAndDuration($distance, $time);
echo $speed->toString(); // 5 m/s
```

### Converting Measurements

[](#converting-measurements)

*Measurement* objects of the same dimension can be converted from one unit of measure to another.

```
use Measurements\Measurement;
use Measurements\Units\UnitLength;

$meters = new Measurement(4.48, UnitLength::meters());

$centimeters = $meters->convertTo(UnitLength::centimeters());
echo $centimeters; // = 448 cm
```

Measurements created as *Quantities* objects also provide a short syntax to convert them. They make use of the `__call()` magic-method to resolve the derived dimension.

```
use Measurements\Quantities\Length;

$meters = Length::meters(4.48);

$centimeters = $meters->toCentimeters();
echo $centimeters; // = 448 cm
```

### Making Arithmetic Operations

[](#making-arithmetic-operations)

*Measurement* objects support different operations, including `add` (`+`), `subtract` (`-`), `multiply` (`*`) and `divide` (`/`). Since *Measurement* objects are immutable, new instances are returned.

```
use Measurements\Measurement;
use Measurements\Units\UnitLength;

$first = new Measurement(4.48, UnitLength::meters());
$second = new Measurement(2.02, UnitLength::meters());

echo $first->add($second); // = 6.5 m

echo $first->subtract($second); // = 2.46 m

echo $first->multiplyBy($second); // = 9.0496 m

echo $first->divideBy($second); // = 2.2178217822 m
```

Conversions are automatically applied while making operations on measurements with different units. The returned measurement is defined in the base unit.

```
use Measurements\Measurement;
use Measurements\Units\UnitLength;

$decimeters = new Measurement(44.8, UnitLength::decimeters());
$centimeters = new Measurement(202, UnitLength::centimeters());

echo $decimeters->add($centimeters); // = 6.5 m

echo $decimeters->subtract($centimeters); // = 2.46 m

echo $decimeters->multiplyBy($centimeters); // = 9.0496 m

echo $decimeters->divideBy($centimeters); // = 2.2178217822 m
```

It is also possible to make arithmetic operations on a measurement using values.

```
use Measurements\Measurement;
use Measurements\Units\UnitLength;

$centimeters = new Measurement(42, UnitLength::centimeters());

echo $centimeters->addValue(8); // = 50 cm

echo $centimeters->subtractValue(12); // = 30 cm

echo $centimeters->multiplyByValue(2); // = 84 cm

echo $centimeters->divideByValue(2); // = 21 cm
```

### Working with Custom Units

[](#working-with-custom-units)

In addition to provided units, you can define custom units. Custom units can be initialized from a symbol and converter of an existing type or implemented as a class method of an existing type for additional convenience. You can also define your own `Dimension` subclass to represent an entirely new unit dimension.

#### Initializing a Custom Unit with a Specified Symbol and Definition

[](#initializing-a-custom-unit-with-a-specified-symbol-and-definition)

The simplest way to define a custom unit is to create a new instance of an existing `Dimension` subclass.

For example, let define a *jump* as a custom, nonstandard unit of length (1 jump = 1.82 m). You can create a new instance of `UnitLength` as follows:

```
$jump = new UnitLength("jump", new UnitConverterLinear(1.82));
```

#### Extending Existing Dimension Subclasses

[](#extending-existing-dimension-subclasses)

Alternatively, you can extend an existing `Dimension` subclass to define a new unit.

For example, let define our new *jump* unit as custom subclass:

```
class UnitJump extends UnitLength {

	public static function jumps()
	{
		return new static("jump", new UnitConverterLinear(1.82));
	}

}
```

#### Creating a Custom Dimension Subclass

[](#creating-a-custom-dimension-subclass)

You can create a new subclass of `Dimension` to describe a new unit dimension.

For example, let define units for digital data. In computing and telecommunications, a unit of information is the capacity of some standard data storage system or communication channel, used to measure the capacities of other systems and channels. Bytes, or multiples thereof, are common units used to specify the sizes of computer files and the capacity of storage units.

You can implement a `UnitDigitalData` class that defines units of digital information as follows:

```
class UnitDigitalData extends Dimension {

	public static function baseUnit()
	{
		return static::bytes();
	}

	public static function bytes()
	{
		return new UnitDigitalData("B", new UnitConverterLinear(1.0));
	}

	public static function kilobytes()
	{
		return new UnitDigitalData("kB", new UnitConverterLinear(1000));
	}

	public static function megabytes()
	{
		return new UnitDigitalData("MB", new UnitConverterLinear(1000000));
	}

	public static function kibibytes()
	{
		return new UnitDigitalData("KiB", new UnitConverterLinear(1024));
	}

	public static function mebibytes()
	{
		return new UnitDigitalData("MiB", new UnitConverterLinear(1048576));
	}

	// ...

}
```

Generating API Documentation
----------------------------

[](#generating-api-documentation)

```
phpdoc -d ./src/ -t ./doc/generated --template="xml"
phpdocmd ./doc/generated/structure.xml doc/
```

License
-------

[](#license)

This library is open-sourced software licensed under the [MIT license](http://opensource.org/licenses/MIT).

###  Health Score

42

—

FairBetter than 88% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity43

Moderate usage in the ecosystem

Community15

Small or concentrated contributor base

Maturity72

Established project with proven stability

 Bus Factor1

Top contributor holds 75% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~408 days

Recently: every ~510 days

Total

6

Last Release

1604d ago

PHP version history (3 changes)v1.0.0PHP &gt;=7.0.0

v1.3.0PHP ^7.2

v1.4.0PHP ^7.2 | ^8.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/ab337f73186ba0b7fb62b7243f485cd94ef9bed64192ed60f22c07bad6edd4d6?d=identicon)[nmarfurt](/maintainers/nmarfurt)

---

Top Contributors

[![marfurt](https://avatars.githubusercontent.com/u/108321?v=4)](https://github.com/marfurt "marfurt (12 commits)")[![johanmeiring](https://avatars.githubusercontent.com/u/1214876?v=4)](https://github.com/johanmeiring "johanmeiring (4 commits)")

---

Tags

measurementsunitsunitconversionmeasurement

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/nmarfurt-measurements/health.svg)

```
[![Health](https://phpackages.com/badges/nmarfurt-measurements/health.svg)](https://phpackages.com/packages/nmarfurt-measurements)
```

###  Alternatives

[cuyz/valinor

Dependency free PHP library that helps to map any input into a strongly-typed structure.

1.5k13.2M174](/packages/cuyz-valinor)[php-unit-conversion/php-unit-conversion

A fully PSR-4 compatible PHP library for converting between standard units of measure.

691.2M2](/packages/php-unit-conversion-php-unit-conversion)[florianv/swap

PHP currency conversion library for retrieving exchange rates from 30+ providers, with caching and fallback.

1.3k6.8M23](/packages/florianv-swap)[spatie/color

A little library to handle color conversions

38221.2M36](/packages/spatie-color)[php-units-of-measure/php-units-of-measure

A PHP library for converting between standard units of measure.

3143.8M35](/packages/php-units-of-measure-php-units-of-measure)[ozdemirburak/iris

PHP library for color manipulation and conversion.

1201.9M23](/packages/ozdemirburak-iris)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
