PHPackages                             sgh/comparable - 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. sgh/comparable

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

sgh/comparable
==============

Provides Comparable and Comparator interfaces and methods to sort and compare objects based on these.

v1.1.1(11y ago)1473.7k↓43.1%12MITPHPPHP &gt;=5.4.0

Since Mar 30Pushed 11y ago1 watchersCompare

[ Source](https://github.com/schmengler/Comparator-Tools)[ Packagist](https://packagist.org/packages/sgh/comparable)[ Docs](https://github.com/schmengler/Comparator-Tools)[ RSS](/packages/sgh-comparable/feed)WikiDiscussions master Synced 1mo ago

READMEChangelogDependencies (1)Versions (4)Used By (2)

Comparable
==========

[](#comparable)

[![Author](https://camo.githubusercontent.com/2e77af773c3c248fbc46eea4a88a1f2328a3d05f48b5e902a58db98ae9055de4/687474703a2f2f696d672e736869656c64732e696f2f62616467652f617574686f722d40667363686d656e676c65722d626c75652e7376673f7374796c653d666c61742d737175617265)](https://twitter.com/fschmengler)[![Latest Version](https://camo.githubusercontent.com/cb448837464e64667754ba529236b3d5d4ad91fb8d0eb11ff729a741580fd013/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f7367682f636f6d70617261626c652e737667)](https://packagist.org/packages/sgh/comparable)[![Software License](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)[![Build Status](https://camo.githubusercontent.com/d1db6c63acbb63adb4d098449cb0903618a2f8e4c9d6706c21c0f6bf4a69f59d/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f7363686d656e676c65722f436f6d70617261746f722d546f6f6c732f6d61737465722e7376673f7374796c653d666c61742d737175617265)](https://travis-ci.org/schmengler/Comparator-Tools)

This package, formerly known as Comparator Tools, provides sorting of objects that have a Comparable interface and other useful functions with comparison of objects. With these tools the `Comparable` and `Comparator` interfaces can be used as known from Java.

Requirements
------------

[](#requirements)

The package requires PHP 5.4 or later. The `2.x` branch requires PHP 5.6 or later.

Install
-------

[](#install)

Via Composer

```
$ composer require sgh/comparable
```

Usage
-----

[](#usage)

To give your classes the comparable functionality, implement the Comparable interface:

```
use SGH\Comparable\Comparable;

class Foo implements Comparable
{
    public function compareTo($object)
    {
        // if $this less than $object,    return -1
        // if $this equals $object,       return 0
        // if $this greater than $object, return 1
    }
}

```

The compareTo method will be called with another instance of Foo as parameter and must return a negative integer value if ($this &lt; $object) applies and a positive integer value if ($this &gt; $object) applies, 0 otherwise (the objects are considered equal). Note that non-integer values will be cast to (int), so that `0.5` will be treated as `0`.

To sort or compare objects with the Comparable interface, you can use the methods in `SortFunctions` and `SetFunctions`.

### Sorting

[](#sorting)

```
use SGH\Comparable\SortFunctions;

SortFunctions::sort($arrayOfFoo);
SortFunctions::asort($arrayOfFoo);
SortFunctions::rsort($arrayOfFoo);
SortFunctions::arsort($arrayOfFoo);
SortFunctions::multisort($arrayOfFoo, $arbitraryArray, ...);

```

The first four methods work analogous to the respective core functions `sort`, `asort`, `rsort` and `arsort`. `multisort` works like `array_multisort` in the "sort multiple arrays" mode, i.e. the first passed array is sorted with the Comparable interface, the others are re-ordered in the same way as the first.

### Comparing

[](#comparing)

```
use SGH\Comparable\SetFunctions;

$diff = SetFunctions::diff($arrayOfFoo1, $arrayOfFoo2, ...);
$diff = SetFunctions::diff_assoc($arrayOfFoo1, $arrayOfFoo2, ...);
$intersect = SetFunctions::intersect($arrayOfFoo1, $arrayOfFoo2, ...);
$intersect = SetFunctions::intersect_assoc($arrayOfFoo1, $arrayOfFoo2, ...);
$unique = SetFunctions::unique($arrayOfFoo);

```

The methods work analogous to the respective core functions `array_diff`, `array_diff_assoc`, `array_intersect`, `array_intersect_assoc` and `array_unique`. They treat objects `$a` and `$b` as equal if and only if `$a->compareTo($b) == 0`.

### Comparators

[](#comparators)

It is also possible to implement the comparison in comparator classes to keep it separated from the objects to compare. This way comparison can be implemented for any values:

```
use SGH\Comparable\Comparator;

class FooComparator implements Comparator
{
    public function compare($object1, $object2)
    {
        // if $object1 less than $object2,    return -1
        // if $object1 equals $object2,       return 0
        // if $object1 greater than $object2, return 1
    }
}

```

The compare method is defined just like the compareTo method but both objects are passed as parameters.

To use a comparator, pass it as last argument to any method of `SetFunctions`and `SortFunctions`:

```
use SGH\Comparable\SortFunctions;
use SGH\Comparable\SetFunctions;

SortFunctions::sort($arrayOfFoo, new FooComparator);
SortFunctions::asort($arrayOfFoo, new FooComparator);
SortFunctions::rsort($arrayOfFoo, new FooComparator);
SortFunctions::arsort($arrayOfFoo, new FooComparator);
SortFunctions::multisort($arrayOfFoo, $arbitraryArray, ..., new FooComparator);

$diff = SetFunctions::diff($arrayOfFoo1, $arrayOfFoo2, ..., new FooComparator);
$diff = SetFunctions::diff_assoc($arrayOfFoo1, $arrayOfFoo2, ..., new FooComparator);
$intersect = SetFunctions::intersect($arrayOfFoo1, $arrayOfFoo2, ..., new FooComparator);
$intersect = SetFunctions::intersect_assoc($arrayOfFoo1, $arrayOfFoo2, ..., new FooComparator);
$unique = SetFunctions::unique($arrayOfFoo, new FooComparator);

```

#### The ObjectComparator

[](#the-objectcomparator)

The package comes with an `ObjectComparator` that compares equality of objects (i.e. if two variables contain the same instance). It provides no useful sort order but can be used with the methods in `SetFunctions` (the core functions `array_diff` etc. cannot compare objects, they try to cast them to string for comparison).

```
use SGH\Comparable\SetFunctions;
use SGH\Comparable\Comparator\ObjectComparator;

$diff = SetFunctions::diff($arrayOfObjects1, $arrayOfObjects2, new ObjectComparator);
// .. and so on

```

The following shortcut methods exist:

```
SetFunctions::objectsDiff($arrayOfObjects1, $arrayOfObjects2);
SetFunctions::objectsIntersect($arrayOfObjects1, $arrayOfObjects2);
SetFunctions::objectsUnique($arrayOfObjects);

```

### SortedIterator

[](#sortediterator)

You can sort iterators as well. Due to the nature of iterators, this means essentially that they get iterated over once, and you get an ArrayIterator with all resulting items, sorted. To sort an iterator, decorate it with the `SortedIterator` like this:

```
use SGH\Comparable\SortFunctions;

$sortedIterator = SortFunctions::sortedIterator($iterator);

```

### Exceptions

[](#exceptions)

The default comparator throws a `ComparatorException` if one of the objects does not implement the `Comparable` interface.

You are encouraged to throw a `ComparatorException` in your `compare()` or `compareTo()` implementations if the objects are not comparable to each other. In most cases you should do it if the objects are not of expected type.

Testing
-------

[](#testing)

```
$ phpunit
```

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

[](#contributing)

Please see [CONTRIBUTING](CONTRIBUTING.md) for details.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- Fabian Schmengler()
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

35

—

LowBetter than 80% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity37

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity60

Established project with proven stability

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 ~6 days

Total

2

Last Release

4061d ago

### Community

Maintainers

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

---

Tags

comparatorcomparable

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/sgh-comparable/health.svg)

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

###  Alternatives

[phootwork/lang

Missing PHP language constructs

1224.8M8](/packages/phootwork-lang)[dragon-code/benchmark

Simple comparison of code execution speed between different options

11934.7k5](/packages/dragon-code-benchmark)[myclabs/array-comparator

Array comparator

19182.5k](/packages/myclabs-array-comparator)[jelix/version

Parse any version syntax, including semantic version. Compare version, using Composer version constraints syntax.

13193.0k4](/packages/jelix-version)

PHPackages © 2026

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