PHPackages                             pckg/collection - 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. pckg/collection

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

pckg/collection
===============

Implementation for more human-like dealing with collections

15.8k1PHPCI failing

Since Dec 21Pushed 1y ago1 watchersCompare

[ Source](https://github.com/pckg/collection)[ Packagist](https://packagist.org/packages/pckg/collection)[ RSS](/packages/pckg-collection/feed)WikiDiscussions next-8.0 Synced 2mo ago

READMEChangelogDependenciesVersions (3)Used By (0)

pckg/collection
===============

[](#pckgcollection)

[![Codacy Badge](https://camo.githubusercontent.com/1f63afa78171661229356a796aad304603945bb63a35a106dd6e25803fb52036/68747470733a2f2f6170692e636f646163792e636f6d2f70726f6a6563742f62616467652f47726164652f6639386134386165343062303433323139356535326334373931313566636666)](https://www.codacy.com/app/schtr4jh/collection?utm_source=github.com&utm_medium=referral&utm_content=pckg/collection&utm_campaign=badger)

[![Build status](https://github.com/pckg/collection/workflows/Pckg%20Collection%20CI/badge.svg)](https://github.com/pckg/collection/workflows/Pckg%20Collection%20CI/badge.svg)

Pckg/collection provides a ways handle collection of items / arrays and strings differently. It works really well with [pckg/skeleton](https://github.com/pckg/skeleton), [pckg/framework](https://github.com/pckg/framework) and [pckg/database](https://github.com/pckg/database).

Installation
============

[](#installation)

For standalone usage simply require pckg/collection in composer.

```
$ composer require pckg/collection
```

For advanced usage check pckg/skeleton.

```
$ composer install pckg/skeleton .
```

Dependencies
------------

[](#dependencies)

Package does not depend on any other package.

Tests
=====

[](#tests)

Test can be run with codeception

```
$ cp ./codeception.sample.yml ./codeception.yml
$ codecept run
```

Simple usage
============

[](#simple-usage)

```
// create a new Collection

$collection = new Collection();

// push items to the last position of the collection

// push some single items

$collection->push('foo');
$collection->push('bar');

// push a whole array

$collection->pushArray(['first', 'second']);

// pop last item and remove it from collection

$item = $collection->pop();

// add an item at the first position

$collection->prepend('prepended');

// retrieve and remove first item

$item = $collection->shift();

// retrieve first and last items keeping then in colection

$collection->first();
$collection->last();
```

Callbacks
=========

[](#callbacks)

has
---

[](#has)

Testing if collection has a set of values:

```
$collection = new Collection([
                                 'foo' => [
                                     'id'    => 1,
                                     'title' => 'baz',
                                 ],
                                 'bar' => [
                                     'id'    => 2,
                                     'title' => 'unknown',
                                 ],
                             ]);

$collection->has(['id' => 1, 'title' => 'baz'])); // return true

$collection->has(['id' => 2, 'title' => 'baz'])); // return false
```

Filtering entries
-----------------

[](#filtering-entries)

Return all itens that has a `true` return from annonymous function.

```
$filtered = $collection->filter(function($item) {
    return $item['id'] == 1;
});

var_dump($filtered->all()); // ['foo' => ['id' => 1, 'title' => 'baz']]
```

Seting keys
-----------

[](#seting-keys)

Set entry keys by some array item value. At following sample all keys are setted by `title` inner array entry.

```
$keyed = $collection->keyBy('title');

var_dump($keyed->all());

/**
* [
*     'baz'     => [
*         'id'    => 1,
*         'title' => 'baz',
*     ],
*     'unknown' => [
*         'id'    => 2,
*         'title' => 'unknown',
*     ],
* ]
**/
```

Get first item by satisfied check
---------------------------------

[](#get-first-item-by-satisfied-check)

Return the firt item that satisfies a logical test.

```
$first = $collection->first(function($item) {
   return $item['id'] > 1;
});

var_dump($first); //['id' => 2, 'title' => 'unknown']
```

Map key by inner value
----------------------

[](#map-key-by-inner-value)

Map the key of each entry to a inner value based on inner key.

```
$mapped = $collection->map('title');

var_dump($mapped->all()); // ['foo' => 'baz', 'bar' => 'unknown']
```

Keys and Values
===============

[](#keys-and-values)

```
$collection = new Collection(['foo' => 'bar', 'baz' => 'test', 'john' => 'doe', 'jane' => 'name']);

// get a collection with a removed entry based on it key

$removedOne = $collection->removeKeys('baz');  // ['foo' => 'bar', 'john' => 'doe', 'jane' => 'name']

// get a collection with several entries removed based on they keys

$removedMultiple = $collection->removeKeys(['baz', 'john']); // ['foo' => 'bar', 'jane' => 'name']

// get a collection with several entries removed based on they values

$removedValues = $collection->removeValues(['bar', 'test']); // ['john' => 'doe', 'jane' => 'name']

// get all keys of a collection

$keys = $collection->keys(); // ['foo', 'baz', 'john', 'jane']

// get all values of a collection

$values = $collection->values(); // ['bar', 'test', 'doe', 'name']

// test if a key exist

$collection->hasKey('baz'); // true
$collection->hasKey('bz'); // false

// retrieve the value of a key

$collection->getKey('baz'); // 'test'
```

Manipulations
=============

[](#manipulations)

Slice a collection
------------------

[](#slice-a-collection)

```
$collection = new Collection(['foo', 'bar', 'baz', '', ' untrimmed ']);

$sliced = $collection->slice(1, 2); // ['bar', 'baz']
```

Chunk
-----

[](#chunk)

Chunk by pieces.

```
$chunked = $collection->chunk(2);

/**
* [
*    ['foo', 'bar'],
*    ['baz', ''],
*    [' untrimmed ']
*
**/
```

Flat
----

[](#flat)

```
$flatten = $chunked->flat(); // ['foo', 'bar', 'baz', '', ' untrimmed ']
```

Trim
----

[](#trim)

```
$trimmed = $collection->trim(); // ['foo', 'bar', 'baz', '', 'untrimmed']
```

Multiply by x
-------------

[](#multiply-by-x)

Duplicate the items by the number passed.

```
$multiplied = $collection->multiply(2);

/**
* [
*    'foo',
*    'bar',
*    'baz',
*    '',
*    ' untrimmed ',
*    'foo',
*    'bar',
*    'baz',
*    '',
*    ' untrimmed ',
* ]
**/
```

unique
------

[](#unique)

Return a collection with no duplicated values

```
$unique = $multiplied->unique(); // ['foo', 'bar', 'baz', '', 'untrimmed']
```

Implode
-------

[](#implode)

Get a string with all collection values separated by imploded char.

```
$imploded = $collection->implode(' ', ' - '); // 'foo bar baz  -  untrimmed '
```

Remove empty values
-------------------

[](#remove-empty-values)

```

$nonEmpty = $collection->removeEmpty(); // ['foo', 'bar', 'baz', ' untrimmed ']
```

Math
====

[](#math)

```
$collection = new Collection([2, 1, 13, 3, 1, 5, 21, 8]);

$sum = $collection->sum(); // 54

$avg = $collection->avg(); // 6.75

$min = $collection->min(); // 1

$max = $collection->max(); // 21
```

###  Health Score

24

—

LowBetter than 32% of packages

Maintenance28

Infrequent updates — may be unmaintained

Popularity20

Limited adoption so far

Community11

Small or concentrated contributor base

Maturity31

Early-stage or recently created project

 Bus Factor1

Top contributor holds 98.9% 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.

### Community

Maintainers

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

---

Top Contributors

[![schtr4jh](https://avatars.githubusercontent.com/u/385801?v=4)](https://github.com/schtr4jh "schtr4jh (178 commits)")[![codacy-badger](https://avatars.githubusercontent.com/u/23704769?v=4)](https://github.com/codacy-badger "codacy-badger (1 commits)")[![nunomazer](https://avatars.githubusercontent.com/u/652935?v=4)](https://github.com/nunomazer "nunomazer (1 commits)")

### Embed Badge

![Health badge](/badges/pckg-collection/health.svg)

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

###  Alternatives

[humanmade/mu-plugins-loader

A WordPress must-use plugin autoloader for mu-plugins in directories

1122.3k](/packages/humanmade-mu-plugins-loader)[caouecs/bootstrap3

Bootstrap 3 for Laravel 4

111.9k](/packages/caouecs-bootstrap3)

PHPackages © 2026

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