PHPackages                             cocur/chain - 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. cocur/chain

ActiveLibrary

cocur/chain
===========

Consistent and chainable array manipulation

v0.9.0(5y ago)8169.6k↓17.3%11[5 issues](https://github.com/cocur/chain/issues)2MITPHPPHP &gt;=7.2

Since Nov 6Pushed 5y ago4 watchersCompare

[ Source](https://github.com/cocur/chain)[ Packagist](https://packagist.org/packages/cocur/chain)[ RSS](/packages/cocur-chain/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (10)Dependencies (1)Versions (21)Used By (2)

Chain
=====

[](#chain)

> Chain provides you with a consistent and chainable way to work with arrays in PHP.

[![Build Status](https://camo.githubusercontent.com/a9bc882351bda7892c6e4816831056ac5131382cc39b03371aefa734927a889e/68747470733a2f2f696d672e736869656c64732e696f2f7472617669732f636f6375722f636861696e2f6d61737465722e7376673f7374796c653d666c6174)](https://travis-ci.org/cocur/chain)[![Windows Build status](https://camo.githubusercontent.com/e5f4c0c8c8fafe8edb2c5d0f75f05d64029af0acdd53ab5402bcf55b63b1d882/68747470733a2f2f63692e6170707665796f722e636f6d2f6170692f70726f6a656374732f7374617475732f7679666773717372783938773864386e3f7376673d74727565)](https://ci.appveyor.com/project/florianeckerstorfer/chain)[![Scrutinizer Code Quality](https://camo.githubusercontent.com/a37d1aad9e7531399817bd763b1164a792f7e733f54ebbc2ad990fc51951ed0e/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f672f636f6375722f636861696e2e7376673f7374796c653d666c6174)](https://scrutinizer-ci.com/g/cocur/chain/?branch=master)[![Code Coverage](https://camo.githubusercontent.com/3ee49b28d5d9f97314e36604a335036981c6d85d1c8d65b518a64c9e6ab7c226/68747470733a2f2f696d672e736869656c64732e696f2f7363727574696e697a65722f636f7665726167652f672f636f6375722f636861696e2e7376673f7374796c653d666c6174)](https://scrutinizer-ci.com/g/cocur/chain/?branch=master)

Made by [Florian Eckerstorfer](https://florian.ec) in Vienna, Europe.

Motivation
----------

[](#motivation)

Let us be honest. Working with arrays in PHP is a mess. First of all, you have to prefix most (but not all) functions with `array_`, the parameter ordering is not consistent. For example, `array_map()` expects the callback as first parameter and the array as the second, but `array_filter()` expects the array as first and the callback as second. You also have to wrap the function calls around the array, the resulting code is not nice to look at, not readable and hard to understand.

```
$arr = array_filter(
    array_map(
        function ($v) { return rand(0, $v); },
        array_fill(0, 10, 20)
    ),
    function ($v) { return $v & 1; }
);
```

Chain wraps the array in an object and gives you a chainable interface.

```
$chain = Chain::fill(0, 10, 20)
    ->map(function ($v) { return rand(0, $v); })
    ->filter(function ($v) { return $v & 1; });
```

Take a look at the following code. How long do you need to understand it?

```
echo array_sum(array_intersect(
    array_diff([1, 2, 3, 4, 5], [0, 1, 9]),
    array_filter([2, 3, 4], function ($v) { return !($v & 1); })
));
```

What about this?

```
echo Chain::create([1, 2, 3, 4, 5])
    ->diff([0, 1, 9])
    ->intersect(Chain::create([2, 3, 4])->filter(function ($v) { return !($v & 1); }))
    ->sum();
```

*Hint: It takes the diff of two arrays, intersects it with a filtered array and sums it up.*

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

[](#installation)

You can install Chain using [Composer](http://getcomposer.org):

```
$ composer require cocur/chain
```

Usage
-----

[](#usage)

Chain allows you to create, manipulate and access arrays.

### Array Creation

[](#array-creation)

You can create a Chain by passing an array to the constructor.

```
$chain = new Chain([1, 2, 3]);
```

Or with a convenient static method:

```
$chain = Chain::create([1, 2, 3]);
```

In addition a Chain can also be created by the static `fill()` method, which is a wrapper for the `array_fill()`function.

```
$chain = Chain::fill(0, 10, 'foo');
```

There is also a method, `::createFromString()`, that creates the Chain from a string. In addition to the string you need to provide a delimiter, which is used to split the string. If the option `regexp` is passed in the delimiter must be a regular expression.

```
Chain::createFromString(',', '1,2,3')->array;                               // -> [1, 2, 3]
Chain::createFromString('/,|.|;/', '1,2.3;4,5', ['regexp' => true])->array; // -> [1, 2, 3, 4, 5]
```

### Array Manipulation

[](#array-manipulation)

Chains manipulation methods manipulate the underlying array and return the object, that is, they can be chained. Most of the methods are simple wrappers around the corresponding `array_` function.

In the following example `->map()` is used to multiply each element by `3` and then filter the array to only contain odd elements.

```
$chain = (new Chain([1, 2, 3]))
    ->map(function ($v) { return $v*3; })
    ->filter(function ($v) { return $v & 1; });
$chain->array; // -> [3, 9]
```

When a method accepts an array (`->diff()` or `->intersect()`) you can also pass in another instance of `Chain`instead of the array.

#### List of Array Manipulation Methods

[](#list-of-array-manipulation-methods)

All of these methods manipulate the array, but not all of them return an instance of `Cocur\Chain\Chain`. For example, `->shift()` removes the first element from the array and returns it.

- `->changeKeyCase()`
- `->combine(array|Chain, array|Chain)`
- `->count()`
- `->diff(array|Chain)`
- `->filter(callable)`
- `->find(callable)`
- `->flatMap(callable)`
- `->flip()`
- `->intersect(array|Chain)`
- `->intersectAssoc(array|Chain)`
- `->intersectKey(array|Chain)`
- `->keys()`
- `->map(callable)`
- `->merge(array|Chain)`
- `->pad(int, mixed)`
- `->pop()`
- `->product()`
- `->push(mixed)`
- `->reduce(callable[, int])`
- `->reverse([bool])`
- `->search(mixed[, bool])`
- `->shift()`
- `->shuffle()`
- `->sort(sortFlags)`
- `->sortKeys(sortFlags)`
- `->splice(offset[, length[, replacement]])`
- `->sum()`
- `->unique()`
- `->unshift(mixed)`
- `->values()`

### Array Access

[](#array-access)

Most importantly you can access the underlying array using the public `array` property.

```
$chain = new Chain([1, 2, 3]);
$chain->array; // -> [1, 2, 3]
```

Chain implements the [Traversable](http://php.net/manual/en/class.traversable.php) interface.

```
$chain = new Chain([1, 2, 3]);
foreach ($chain as $key => $value) {
  // ...
}
```

It also implements the [ArrayAccess](http://php.net/manual/en/class.arrayaccess.php) interface allowing to access elements just like in any normal array.

```
$chain = new Chain();
$chain['foo'] = 'bar';
if (isset($chain['foo'])) {
    echo $chain['foo'];
    unset($chain['foo']);
}
```

Additionally `Chain` contains a number of methods to access properties of the array. In contrast to the manipulation methods these methods return a value instead of a reference to the `Chain` object. That is, array access methods are not chainable.

```
$chain = new Chain([1, 2, 3]);
$chain->count(); // -> 3
$chain->sum();   // -> 6
$chain->first(); // -> 1
$chain->last();  // -> 3

$chain->reduce(function ($current, $value) {
    return $current * $value;
}, 1); // -> 6
```

### List of Array Access Methods

[](#list-of-array-access-methods)

- `->count()`
- `->countValues()`
- `->every(callable)`
- `->first()`
- `->includes(mixed[, array])`
- `->join([$glue])`
- `->last()`
- `->reduce()`
- `->some()`
- `->sum()`

Author
------

[](#author)

Chain has been developed by [Florian Eckerstorfer](https://florian.ec) ([Twitter](https://twitter.com/Florian_)) in Vienna, Europe.

> Chain is a project of [Cocur](http://cocur.co). You can contact us on Twitter: [**@cocurco**](https://twitter.com/cocurco)

Support
-------

[](#support)

If you need support you can ask on [Twitter](https://twitter.com/cocurco) (well, only if your question is short) or you can join our chat on Gitter.

[![Gitter](https://camo.githubusercontent.com/abe08b740a4156153736f791393ec4da6619c4be73212e75769f52edacc0e2b5/68747470733a2f2f6261646765732e6769747465722e696d2f4a6f696e253230436861742e737667)](https://gitter.im/cocur/chain)

In case you want to support the development of Chain you can [send me an Euro or two](https://paypal.me/florianec/2).

Change Log
----------

[](#change-log)

### Version 0.9.0 (19 July 2020)

[](#version-090-19-july-2020)

- [\#42](https://github.com/cocur/chain/pull/42) Refactor to support strong typing (by [nreynis](https://github.com/nreynis))
- [\#45](https://github.com/cocur/chain/pull/45) Use self return type (by [nreynis](https://github.com/nreynis))
- [\#46](https://github.com/cocur/chain/pull/46) Bugfixes for splice and replace (by [nreynis](https://github.com/nreynis))
- [\#47](https://github.com/cocur/chain/pull/47) Handle invalid patterns in createFromString (by [nreynis](https://github.com/nreynis))
- [\#49](https://github.com/cocur/chain/pull/49) Move static factory fill method (by [nreynis](https://github.com/nreynis))
- [\#50](https://github.com/cocur/chain/pull/50) Add includes (in\_array) (by [nreynis](https://github.com/nreynis))
- [\#51](https://github.com/cocur/chain/pull/51) Add every (by [nreynis](https://github.com/nreynis))
- [\#52](https://github.com/cocur/chain/pull/52) Add some (by [nreynis](https://github.com/nreynis))

### Version 0.8.0 (12 September 2019)

[](#version-080-12-september-2019)

- [\#40](https://github.com/cocur/chain/pull/40) Update tooling and dependencies, set minimum PHP version to 7.2
- [\#37](https://github.com/cocur/chain/pull/37) Add missing traits `\Cocur\Chain\Chain` (by [nreynis](https://github.com/nreynis))
- [\#41](https://github.com/cocur/chain/pull/41) Add `➞ flatMap()` (by [nreynis](https://github.com/nreynis))

### Version 0.7.0 (11 November 2018)

[](#version-070-11-november-2018)

- [\#28](https://github.com/cocur/chain/pull/28) Fix `->slice()` (by [Arpple](https://github.com/Arpple))
- [\#29](https://github.com/cocur/chain/pull/29) Pass key to callback in `->filter()` (by [silvadanilo](https://github.com/silvadanilo))
- [\#30](https://github.com/cocur/chain/pull/30) Pass key to callback in `->map()` (by [silvadanilo](https://github.com/silvadanilo))
- [\#31](https://github.com/cocur/chain/pull/31) Add `->values()` link (by [florianeckerstorfer](https://github.com/florianeckerstorfer))

### Version 0.6.0 (5 April 2018)

[](#version-060-5-april-2018)

- [\#23](https://github.com/cocur/chain/pull/23) Add JsonSerializable to Chain (by [florianeckerstorfer](https://github.com/florianeckerstorfer))

### Version 0.5.0 (4 December 2017)

[](#version-050-4-december-2017)

- [\#19](https://github.com/cocur/chain/pull/19) Add `Join` link (by [florianeckerstorfer](https://github.com/florianeckerstorfer))

### Version 0.4.1 (4 December 2017)

[](#version-041-4-december-2017)

- Add `Find` link to `Cocur\Chain\Chain`

### Version 0.4.0 (22 September 2017)

[](#version-040-22-september-2017)

- [\#17](https://github.com/cocur/chain/pull/17) Add `Find` link (by [gries](https://github.com/gries))

### Version 0.3.0 (7 September 2017)

[](#version-030-7-september-2017)

- [\#12](https://github.com/cocur/chain/pull/13) Restore constructor (by [sanmai](https://github.com/sanmai))
- Move first() and last() methods into traits
- Add additional links (`CountValues`, `KeyExists`, `Splice`)
- Update `Merge` link

### Version 0.2.0 (6 November 2015)

[](#version-020-6-november-2015)

- [\#11](https://github.com/cocur/chain/pull/11) Add `Cocur\Chain\Chain::createFromString()` to create a chain from a string
- [\#10](https://github.com/cocur/chain/pull/10) Add methods to `Cocur\Chain\AbstractChain` to retrieve first and last element of chain.
- [\#9](https://github.com/cocur/chain/pull/9) `Cocur\Chain\Chain` is now countable

### Version 0.1.0 (6 November 2015)

[](#version-010-6-november-2015)

- *Initial release*

License
-------

[](#license)

The MIT license applies to Chain. For the full copyright and license information, please view the [LICENSE](https://github.com/cocur/vale/blob/master/LICENSE) file distributed with this source code.

###  Health Score

38

—

LowBetter than 84% of packages

Maintenance19

Infrequent updates — may be unmaintained

Popularity44

Moderate usage in the ecosystem

Community20

Small or concentrated contributor base

Maturity57

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 60% 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 ~107 days

Recently: every ~209 days

Total

17

Last Release

2119d ago

PHP version history (2 changes)v0.3PHP &gt;=5.6

v0.8.0PHP &gt;=7.2

### Community

Maintainers

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

---

Top Contributors

[![florianeckerstorfer](https://avatars.githubusercontent.com/u/149201?v=4)](https://github.com/florianeckerstorfer "florianeckerstorfer (45 commits)")[![nreynis](https://avatars.githubusercontent.com/u/1766299?v=4)](https://github.com/nreynis "nreynis (15 commits)")[![gries](https://avatars.githubusercontent.com/u/417823?v=4)](https://github.com/gries "gries (9 commits)")[![sanmai](https://avatars.githubusercontent.com/u/139488?v=4)](https://github.com/sanmai "sanmai (2 commits)")[![silvadanilo](https://avatars.githubusercontent.com/u/344657?v=4)](https://github.com/silvadanilo "silvadanilo (1 commits)")[![davidmz](https://avatars.githubusercontent.com/u/132120?v=4)](https://github.com/davidmz "davidmz (1 commits)")[![peter279k](https://avatars.githubusercontent.com/u/9021747?v=4)](https://github.com/peter279k "peter279k (1 commits)")[![Arpple](https://avatars.githubusercontent.com/u/12965313?v=4)](https://github.com/Arpple "Arpple (1 commits)")

---

Tags

arrayarray-manipulationschainable-methods

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/cocur-chain/health.svg)

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

PHPackages © 2026

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