PHPackages                             jakewhiteley/php-sets - 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. jakewhiteley/php-sets

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

jakewhiteley/php-sets
=====================

An implementation of a Java-like Set data structure for PHP. A Set is an iterable data structure which allows strict-type storage of unique values.

1.3.0(2y ago)1827.5k↓29.5%2[1 PRs](https://github.com/jakewhiteley/php-sets/pulls)GPL-3.0-or-laterPHPPHP &gt;=7.4CI passing

Since Dec 12Pushed 3mo ago1 watchersCompare

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

READMEChangelog (4)Dependencies (1)Versions (7)Used By (0)

[![Travis (.com)](https://camo.githubusercontent.com/7c1610f1249ac2f88034416638df15a047d6aa85ec8cc37b7baded69b12edda1/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f636f6d2f6a616b6577686974656c65792f7068702d736574733f7374796c653d666c61742d737175617265)](https://travis-ci.com/jakewhiteley/php-sets) [![Coveralls github](https://camo.githubusercontent.com/a8fc4430faff7ab151b1f253e9ed6d632c6143fac03cbcfb8096ddf9511ea35a/68747470733a2f2f696d672e736869656c64732e696f2f636f766572616c6c732f6769746875622f6a616b6577686974656c65792f7068702d736574733f7374796c653d666c61742d737175617265)](https://coveralls.io/github/jakewhiteley/php-sets)

php-set-data-structure
======================

[](#php-set-data-structure)

A PHP implementation of a Java-like Set data structure.

A set is simply a group of unique things that can be iterated by the order they were inserted. So, a significant characteristic of any set is that it does not contain duplicates.

Implementation is based on the [MDN JS Reference](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Set) for Sets in EMCA 6 JavaScript.

Sets require a min PHP version of 7.4.

- [Installation](#installation)
- [**Basic usage:**](#basic-usage)
    - [Creating a Set](#creating-a-set)
    - [Adding values](#adding-values)
    - [Removing values](#removing-values)
    - [Testing if a value is present](#testing-if-a-value-is-present)
    - [Counting items](#counting-items)
- [**Set Iteration**](#iteration)
    - [As a traditional Array](#as-a-traditional-array)
    - [Using `entries()`](#using-entries)
    - [Using `each`](#using-eachcallback-args)
- [**Set operations**](#set-operations)
    - [Union](#union)
    - [Difference](#difference)
    - [Symmetric difference](#symmetric-difference)
    - [Intersect](#intersect)
    - [Subsets](#subsets)
- [**Set family operations**](#set-family-operations)
    - [Family Union](#union-of-a-family-of-sets)
    - [Family Intersection](#intersection-of-a-family-of-sets)

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

[](#installation)

You can download the latest release via the releases link on this page.

PHP-Sets is available via [Composer](https://packagist.org/packages/jakewhiteley/php-sets) by running the following command:

```
composer require jakewhiteley/php-sets
```

then include the library in your project like so:

```
include('vendor/autoload.php');

use PhpSets\Set;
```

Basic Usage
-----------

[](#basic-usage)

#### Creating a Set

[](#creating-a-set)

When you create a set, you can insert initial values or keep it empty.

```
$set = new Set(1, 2, 3);
$emptySet = new Set();
```

Sets cannot contain duplicate values, and values are stored in insertion order.

```
// $set contains [1, 2, 3] as duplicates are not stored
$set = new Set(1, 2, 1, 3, 2);
```

If you have an array of elements, you can either pass in the array directly, or splat the array.

```
$set = new Set([1, 2, 1, 3, 2]);

$array = [1, 2, 1, 3, 2];
$set = new Set(...$array);
```

#### Adding values

[](#adding-values)

Values of any type (Including Objects, arrays, and other `Sets`) are added to a set via the `add()` method.

It is worth noting that uniqueness is on a **strict type** basis, so `(string) '1' !==  (int) 1 !==  (float) 1.0`. This also is true for Objects within the set and an object with a classA is not equal to an object with classB, even if the properties etc are the same.

```
// create empty Set
$set = new Set();

$set->add('a');
// $set => ['a']

$set->add(1);
// $set => ['a', 1]
```

As `Sets` implements the `ArrayAccess` interface, you can also add values as you would with a standard Array.

```
$set = new Set();

$set[] = 1;
$set[] = 'foo';
// $set => [1, 'foo']

// You can also replace values by key, provided the new value is unique within the Set
$set[0] = 2;
// $set => [2, 'foo']

// If a key is not currently in the array, the value is appended to maintain insertion order
$set[4] = 'foo';
// $newSet => [2, 'foo', 'foo']
```

#### Removing values

[](#removing-values)

Values can be removed individually via `delete()`, or all at once via the `clear()` method.

```
$set = new Set(1, 2, 3);

$set->delete(2);
// $set => [1, 3]

$set->clear();
// $set => []
```

You can also delete methods via `ArrayAccess`:

```
$set = new Set(1, 2, 3);

unset($set[0]);
// $set => [2, 3]
```

#### Testing if a value is present

[](#testing-if-a-value-is-present)

You can easily test if a `Set` contains a value via the `has($value)` method.

As with the other methods, this is a **strict type** test.

```
$set = new Set('a', [1, 2], 1.0);

$set->has('a');      // true
$set->has([1, 2]);   // true
$set->has(1);        // false
$set->has([1, '2']); // false
$set->has('foo');    // false
```

#### Counting items

[](#counting-items)

This is done using the `count` method:

```
$set = new Set(1, 2, 3);

echo $set->count(); // 3
```

Iteration
---------

[](#iteration)

There are many ways to iterate a `Set`:

- Like a traditional PHP array
- Using `entries()` to return an instance of PHP's `ArrayIterator`
- Using `each()` and a provided callback function
- Using `values()` which returns a traditional PHP Array version of the Set

#### As a traditional Array

[](#as-a-traditional-array)

The Set object extends an `ArrayObject`, and can be iterated like a normal array:

```
$set = new Set(1, 2);

foreach ($set as $val) {
    print($val);
}
```

Or if you want, you can iterate `$set->values()` instead.

#### Using `entries()`

[](#using-entries)

The `entries()` method returns an [ArrayIterator](http://php.net/manual/en/class.arrayiterator.php) object.

```
$iterator = $set->entries();

while ($iterator->valid()) {
    echo $iterator->current();
    $iterator->next();
}
```

#### Using `each($callback, ...$args)`

[](#using-eachcallback-args)

You can also iterate a `Set` via a provided [callable](https://www.php.net/manual/en/language.types.callable.php) method.

The callback is called with the current item as parameter 1, with any additional specified params passed after.

```
function cb($item, $parameter) {
  echo $item * $parameter;
}

$set = new Set(1, 2);

$set->each('cb', 10);
// prints 10 20
```

Set operations
--------------

[](#set-operations)

#### Union

[](#union)

Appends a second `Set` onto a given `Set` without creating duplicates:

```
$a = new Set(1, 2, 3);
$b = new Set(2, 3, 4);

$merged = $a->union($b);

print_r($merged->values()); // [1, 2, 3, 4]
```

#### Difference

[](#difference)

The `difference()` method will return a new `Set` containing values present in the original `Set` but not present in another.

This is also known as the *relative complement*.

```
$a = new Set(1, 2, 3, 4);
$b = new Set(3, 4, 5, 6);

print_r($a->difference($b)->values()); // [1, 2]
print_r($b->difference($a)->values()); // [5, 6]
```

#### Symmetric Difference

[](#symmetric-difference)

The `symmetricDifference()` method also returns a new `Set` but differs to the `difference` method in that it will return **all** uncommon values between both `Sets`.

```
$a = new Set(1, 2, 3, 4);
$b = new Set(3, 4, 5, 6);

print_r($a->symmetricDifference($b)->values()); // [1, 2, 5, 6]
```

#### Intersect

[](#intersect)

Returns a new `Set` containing the items common (present in both) between two sets:

```
$a = new Set(1, 2, 3);
$b = new Set(2, 3, 4);

$intersect = $a->intersect($b);

print_r($intersect->values()); // [2, 3]
```

#### Subsets

[](#subsets)

The `isSupersetOf` method returns a `bool` indicating if a given `Set` is a subset of the current `Set`.

The order of values does not matter, but a subset must only contain items present in the original `Set`:

```
$a = new Set(1, 2, 3);
$b = new Set(2, 3);

var_Dump($b->isSupersetOf($a)); // true
var_Dump($a->isSupersetOf($b)); // false
```

Set family operations
---------------------

[](#set-family-operations)

If we have a collection of sets, for example `{ { 1,2,3 }, { 3,4,5 } , { 3, 5, 6, 7 } }`, often called a *family* of sets in Set Theory, we can take the union and intersection of the family. That is, `( { 1, 2, 3 } union { 3, 4, 5 } ) union { 3, 5, 6, 7 }` and likewise for intersection. In Set Theory a large union and intersection symbol is used for this purpose.

Note that, at present, these operations are implemented naively by iteratively calling the `union` and `intersect`methods above. More efficient implementations are possible and welcome.

#### Union of a Family of Sets

[](#union-of-a-family-of-sets)

At present the family of sets needs to be in an array of `Set` objects:

```
$set1 = Set(1, 2, 3);
$set2 = Set(3, 4, 5);
$set2 = Set(5, 1, 6);

$set_union = Set::familyUnion([$set1, $set2]); // [1, 2, 3, 4, 5, 6]
```

#### Intersection of a Family of Sets

[](#intersection-of-a-family-of-sets)

As with `familyUnion`, the family of sets needs to be in an array of `Set` objects:

```
$set1 = Set(1,2,3);
$set2 = Set(3,4,5);
$set_family = [ $set1, $set2 ];
$set_intersection = Set::familyIntersection($set_family);
```

Note that, contrary to Set Theory, the result of taking the intersection of an empty array results in an empty array. (In Set Theory the intersection of an empty family is undefined as it would be the ['set of all sets'](https://en.wikipedia.org/wiki/Universal_set).)

### Contributing

[](#contributing)

Contributions and changes welcome! Just open an issue or submit a PR 💪

###  Health Score

46

—

FairBetter than 93% of packages

Maintenance53

Moderate activity, may be stable

Popularity36

Limited adoption so far

Community12

Small or concentrated contributor base

Maturity67

Established project with proven stability

 Bus Factor1

Top contributor holds 95.7% 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 ~786 days

Total

4

Last Release

1083d ago

PHP version history (3 changes)1.0.0PHP ^5.4 || ^7.0

1.2.0PHP &gt;=7.1

1.3.0PHP &gt;=7.4

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/3481634?v=4)[jake whiteley](/maintainers/JakeWhiteley)[@jakewhiteley](https://github.com/jakewhiteley)

---

Top Contributors

[![jakewhiteley](https://avatars.githubusercontent.com/u/3481634?v=4)](https://github.com/jakewhiteley "jakewhiteley (67 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (2 commits)")[![johnallsup](https://avatars.githubusercontent.com/u/1301640?v=4)](https://github.com/johnallsup "johnallsup (1 commits)")

---

Tags

data-structuresinsertion-orderphpphp-setssetsunique-values

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/jakewhiteley-php-sets/health.svg)

```
[![Health](https://phpackages.com/badges/jakewhiteley-php-sets/health.svg)](https://phpackages.com/packages/jakewhiteley-php-sets)
```

###  Alternatives

[elegantly/livewire-modal

Modal for your Livewire App. Done right.

493.6k1](/packages/elegantly-livewire-modal)[fof/mason

Add custom fields to discussions

206.0k](/packages/fof-mason)

PHPackages © 2026

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