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(2mo ago)88.4k↓23.1%5MITPHPPHP ^8.2

Since Jun 4Pushed 2mo ago2 watchersCompare

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

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

56

—

FairBetter than 98% of packages

Maintenance82

Actively maintained with recent releases

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

89d 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

[livewire/flux

The official UI component library for Livewire.

9475.0M86](/packages/livewire-flux)[jantinnerezo/livewire-alert

This package provides a simple alert utilities for your livewire components.

8041.2M20](/packages/jantinnerezo-livewire-alert)[spatie/laravel-livewire-wizard

Build wizards using Livewire

4061.0M4](/packages/spatie-laravel-livewire-wizard)[kirschbaum-development/commentions

A package to allow you to create comments, tag users and more

12369.2k](/packages/kirschbaum-development-commentions)[revolution/self-ordering

Self Ordering System

2112.7k](/packages/revolution-self-ordering)[joelwmale/livewire-quill

Easily add QuillJS with image support to any Laravel Livewire component.

1314.0k](/packages/joelwmale-livewire-quill)

PHPackages © 2026

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