PHPackages                             teamchallengeapps/distance - 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. teamchallengeapps/distance

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

teamchallengeapps/distance
==========================

PHP Distance (Value Object) Helper

2.1.1(4mo ago)89.2k↓60.1%5MITPHPPHP ^8.2CI failing

Since Jun 4Pushed 4mo ago2 watchersCompare

[ Source](https://github.com/teamchallengeapps/distance)[ Packagist](https://packagist.org/packages/teamchallengeapps/distance)[ RSS](/packages/teamchallengeapps-distance/feed)WikiDiscussions master Synced today

READMEChangelog (10)Dependencies (5)Versions (12)Used By (0)

Distance Helper [![Build Status](https://camo.githubusercontent.com/dc621dfad8f97177a98317831f29403ebcb0bf2c59cd9db0a80f57b42210828a/68747470733a2f2f7472617669732d63692e6f72672f7465616d6368616c6c656e6765617070732f64697374616e63652e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/teamchallengeapps/distance)
=============================================================================================================================================================================================================================================================================================================================

[](#distance-helper-)

About
-----

[](#about)

This Distance Helper package contains a tested PHP Value Object which makes working with, comparing, converting and formatting distances (inches, centimeters, meters, kilometers, miles and steps) easy and fluent.

The inspiration for the package came from PHP helpers like [Carbon](http://carbon.nesbot.com/), and an effort to refactor the code behind the virtual workplace walking challenge system [Big Team Challenge](https://bigteamchallenge.com).

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

[](#installation)

You can pull in this package through composer

```
composer require teamchallengeapps/distance

```

The package (particularly configuration) is designed to work with Laravel 10+ using autodiscovery. You can manually add our service provider within the providers array:

```
\TeamChallengeApps\Distance\DistanceServiceProvider::class,

```

Usage
-----

[](#usage)

To create a new distance you, simply new-up an instance of the Distance class.

```
use TeamChallengeApps\Distance\DistanceValue;
use TeamChallengeApps\Distance\Unit;

$meters = new DistanceValue(100, Unit::Meters);
$km = new DistanceValue(10.5, Unit::Kilometers);
$miles = new DistanceValue(10, Unit::Miles);
$steps = new DistanceValue(10000, Unit::Footsteps);
```

The default (base) unit is **centimeters**, so ommitting the second (optional) constructor argument will default to meters. This is chosen to be the smallest (integer) measurement in your datastore - similar to storing integer cents rather than decimal dollars for money.

```
$centimeters = new DistanceValue(100);
```

API
---

[](#api)

### Converting

[](#converting)

You can convert a distance object to a new unit using the `convertTo` methods.

```
use TeamChallengeApps\Distance\DistanceValue;
use TeamChallengeApps\Distance\Unit;

$centimeters = new DistanceValue(1000, Unit::Centimeters);
$meters = $centimeters->convertTo(Unit::Meters);

echo $meters->getValue(); // 1
```

If you want to convert to the base unit (`centimeters` by default), you can do:

```
$distance->convertToBase();
```

The conversions are stored inside the `distance.conversions` config in the format, e.g:

```
'conversions' => [
    'centimeters:meters' => 0.01,
    ...
]

```

### Comparison

[](#comparison)

**Empty / zero**

```
use TeamChallengeApps\Distance\DistanceValue;

$distance new DistanceValue(0);
// or $distance = DistanceValue::zero();

if ($distance->isZero()) {

}
```

**Positive / negative**

```
use TeamChallengeApps\Distance\DistanceValue;

$distance new DistanceValue(100);

$distance->isPositive(); // true
$distance->isNegative(); // false
```

**Value Comparison**

You can compare two distances, but you will get a `ComparisonException` exception if the units do not match

```
use TeamChallengeApps\Distance\DistanceValue;

$distance = new DistanceValue(10);
$total = new DistanceValue(100);

if ($distance->equals($total) ) {
  // Equal to
}

if ($distance->lessThan($total) || $distance->lt($total)) {
  // Less than || alias
}

if ($distance->lessThanOrEqual($total) || $distance->lte($total)) {
  // Less than or equal || alias
}

if ($distance->greaterThan($total) || $distance->gt($total)) {
  // Greater than || alias
}

if ($distance->greaterThanOrEqual($total) || $distance->gte($total)) {
  // Greater than or equal || alias
}
```

### Calculations

[](#calculations)

**Percentage**

```
use TeamChallengeApps\Distance\DistanceValue;

$distance = new DistanceValue(10);
$total = new DistanceValue(100);

$percentage = $distance->percentageOf($total); // 10
```

By default, the real percentage returned, but passing `false` as the second parameter will cap at 100.

```
use TeamChallengeApps\Distance\DistanceValue;

$distance = new DistanceValue(150);
$total = new DistanceValue(100);

$percentage = $distance->percentageOf($total); // 150
$percentage = $distance->percentageOf(distance: $total, overflow: false); // 100
```

**Add**

```
use TeamChallengeApps\Distance\DistanceValue;

$total = new DistanceValue(1000);
$logged = new DistanceValue(10);

$result = $total->add($logged);

echo $result->getValue(); // 1010
```

**Subtract**

```
$total = new DistanceValue(1010);
$redeemed = new DistanceValue(10);

$result = $total->subtract($logged);

echo $result->getValue(); // 1000
```

**Multiply**

```
use TeamChallengeApps\Distance\DistanceValue;

$value = new DistanceValue(5);

$result = $total->multiply(3);

echo $result->getValue(); // 15
```

**Divide**

```
use TeamChallengeApps\Distance\DistanceValue;

$value = new DistanceValue(15);

$result = $total->divide(3);

echo $result->getValue(); // 5
```

### Formatting

[](#formatting)

#### String

[](#string)

Using PHP's magic `__toString()` method, echo-ing or casting the object itself will round and use php-intl's NumberFormatter to render as a string.

```
use TeamChallengeApps\Distance\DistanceValue;

$distance = new DistanceValue(100500.591);

echo $distance; // 100,500.59 centimeters

$value = (string) $distance;

echo $value; // "100,500.59 centimeters"
```

You can change the default precision (2) and rounding mode for each unit in the config file:

```
php artisan vendor:publish --provider="TeamChallengeApps\Distance\DistanceServiceProvider" --tag="config"

```

```
return [

    'formatting' => [
        'precision' => [
            'footsteps' => 0,
            'inches' => 0,
        ],
        'translation' => [
            /* Set if you wish to use Laravel pluralization of unit strings */
            'choice' => true,
        ],
        'round' => [
            'footsteps' => \TeamChallengeApps\Distance\RoundingMode::CEILING,
        ],
    ]

];
```

You can also pass options each time you use format:

```
use TeamChallengeApps\Distance\DistanceValue;
use TeamChallengeApps\Distance\Unit;

$meters = new DistanceValue(1.00005, Unit::Meters);

/** Default - auto converted to centimeters (default display) and rounded to 2 decimal places */
echo $meters->format(); // 100.01 centimeters

/** Not converted from original unit but still rounded and using singular suffix */
echo $meters->format(convert: false); // 1 meter

/** Not converted from original unit but still rounded and using singular translated suffix */
echo $meters->format(convert: false, options: ['precision' => 4, 'unit' => false]); // 1.0001
```

#### Abbreviated

[](#abbreviated)

There is also an abbreviated string helper for steps:

```
use TeamChallengeApps\Distance\DistanceValue;
use TeamChallengeApps\Distance\Unit;

$steps = new DistanceValue(124000, Unit::Footsteps);
echo $steps->formatUsing(formatter: "abbreviated", convert: false); // 124k steps
```

#### Decimal

[](#decimal)

```
use TeamChallengeApps\Distance\DistanceValue;
use TeamChallengeApps\Distance\Unit;

$distance = new DistanceValue(100, Unit::Meters);
echo $distance->formatDecimal(convert: false)); // 100.0

$distance = new DistanceValue(100.56678, Unit::Meters);
echo $distance->formatDecimal(convert: false)); // 100.57

$distance = new DistanceValue(100.56678, Unit::Meters);
echo $distance->formatDecimal(convert: false, options: ['precision' => 3])); // 100.567
```

Contributing
------------

[](#contributing)

Please submit improvements and fixes :)

Changelog
---------

[](#changelog)

Look at the **[CHANGELOG.md](https://github.com/teamchallengeapps/distance/blob/master/CHANGELOG.md)** for this package.

Author
------

[](#author)

[David Rushton](https://github.com/davidrushton) - [Team Challenge Apps Ltd](https://bigteamchallenge.com)

###  Health Score

54

—

FairBetter than 96% of packages

Maintenance75

Regular maintenance activity

Popularity32

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity82

Battle-tested with a long release history

 Bus Factor1

Top contributor holds 100% 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 ~354 days

Recently: every ~263 days

Total

11

Last Release

135d ago

Major Versions

1.x-dev → 2.0.02025-11-17

PHP version history (3 changes)1.0.0PHP &gt;=5.4.0

1.3.0PHP ^7.2|^8.0.2

2.0.0PHP ^8.2

### Community

Maintainers

![](https://www.gravatar.com/avatar/0b1eb2c68ae9c43fc61ae8aa21aabaf932fcb1fd2372e77db8e7800d38cdf3d2?d=identicon)[papertank](/maintainers/papertank)

---

Top Contributors

[![davidrushton](https://avatars.githubusercontent.com/u/4039772?v=4)](https://github.com/davidrushton "davidrushton (33 commits)")

---

Tags

distance-helperlaravel-packagemetersphp-helpers

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/teamchallengeapps-distance/health.svg)

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

###  Alternatives

[illuminate/database

The Illuminate Database package.

2.8k54.9M11.6k](/packages/illuminate-database)[livewire/flux

The official UI component library for Livewire.

9527.8M128](/packages/livewire-flux)[tallstackui/tallstackui

TallStackUI is a powerful suite of Blade components that elevate your workflow of Livewire applications.

725172.4k14](/packages/tallstackui-tallstackui)[illuminate/validation

The Illuminate Validation package.

18838.2M1.7k](/packages/illuminate-validation)[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[venturedrake/laravel-crm

A free open source CRM built as a package for laravel projects

43311.1k](/packages/venturedrake-laravel-crm)

PHPackages © 2026

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