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

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

colindecarlo/collection
=======================

Collection is a collection library focused on delivering faster access to and iteration of its members.

0.1.0(10y ago)523MITPHP

Since Mar 8Pushed 10y ago1 watchersCompare

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

READMEChangelogDependencies (1)Versions (5)Used By (0)

[![Build Status](https://camo.githubusercontent.com/4c1b73947d1d4874c44ae8830fe5232e1d701c85c5c4c70888acf82648f026be/68747470733a2f2f7472617669732d63692e6f72672f636f6c696e64656361726c6f2f636f6c6c656374696f6e2e7376673f6272616e63683d6d6173746572)](https://travis-ci.org/colindecarlo/collection)

Collection
==========

[](#collection)

Collection is a library geared towards delivering a fast and intuitive interface over a group of related elements.

Defining a Collection
---------------------

[](#defining-a-collection)

Collections can be constructed in multiple ways by passing:

- an integer to the constructor indicating its capacity
- an array or [SplFixedArray](splfixedarray) containing the elements of the collection

### Defining an Empty Collection

[](#defining-an-empty-collection)

Empty collections are created by passing an integer to the Collection constructor indicating its capacity. All indexes of the collection are initalized to `null` and the size of the collection is reported as `0`.

```
$imEmpty = new Collection(10);

count($imEmpty);
// 0
```

### Defining a Collection Derived From An `array` or `SplFixedArray`

[](#defining-a-collection-derived-from-an-array-or-splfixedarray)

Collections can be defined using a populated array (or SplFixedArray) simply by passing the array to Collection constructor. The size of the Collection is determined by finding the last non-null index of the array.

```
$daysOfTheWeek = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
$fromArray = new Collection($daysOfTheWeek);

count($fromArray);
// 7
```

```
$occupations = new \SplFixedArray(10);
$occupations[0] = 'Botanist';

$occupations = new Collection($occupations);

count($occupations);
// 1
```

Using Collection
----------------

[](#using-collection)

### map($func)

[](#mapfunc)

Use `map` to create a new instance of Collection which contains a projection of each element of the mapped collection. The projection is created by applying the function contained in `$func` to each element of the original collection.

#### Parameters

[](#parameters)

 `$func` The function which is applied to each element of the collection. `$func` can be any \[callable\](callable) function. #### Example

[](#example)

```
// using a function name
$words = new Collection(['Lorem', 'ipsum', 'dolor', 'sit' 'amet']);
$shouty = $words->map('strtoupper');
// ['LOREM', 'IPSUM', 'DOLOR', 'SIT' 'AMET'];

// using a callable array
$classesToMock = new Collection(['SomeClass', 'SomeOtherClass', 'YetAnotherClass']);
$mocks = $classesToMack->map(['Mockery', 'mock']);
//[object(Mockery\Mock), object(Mockery\Mock), object(Mockery\Mock)]

// using an anonymous function
$stringyDates = new Collection(['2007-06-08', '2009-05-11', '2014-02-19']);
$dates = $stringyDates->map(function ($date) {
  return DateTime::createFromFormat('Y-m-d', $date);
});
// [object(DateTime), object(DateTime), object(DateTime)]
```

### each($func)

[](#eachfunc)

Apply `$func` to each element of the collection. `each` returns the original collection so you can chain other methods off of it.

#### Parameters

[](#parameters-1)

 `$func` The function which is applied to each element of the collection. `$func` can be any \[callable\](callable) function. #### Example

[](#example-1)

```
$queueEmail = function ($address) use ($message, $emailQueue) {
    $emailQueue->publish(['to' => $address, 'message' => $message]);
};

$adminEmails->each($queueEmail);
```

### reduce($func, $intial)

[](#reducefunc-intial)

Generate a single aggregate value derived from applying `$func` to each element of the collection.

#### Parameters

[](#parameters-2)

 `$func` The reducer function, this function accepts two parameters, `$carry` and `$elem` (in that order) where `$carry` is the current value of the reduction and `$elem` is the current element in the collection being reduced. `$func` can be any \[callable\](callable) function.  `$initial` The initial value to be used in the reduction#### Example

[](#example-2)

```
$workSchedule = new Collection([
     ['date' => '2015/04/20', 'start' => '08:00', 'end' => '12:00'],
     ['date' => '2015/04/21', 'start' => '12:00', 'end' => '17:00'],
     ['date' => '2015/04/23', 'start' => '08:00', 'end' => '17:00'],
     ['date' => '2015/04/24', 'start' => '10:00', 'end' => '15:00']
]);

$totalHours = $workSchedule->reduce(function($total, $schedule) {
    $start = DateTime::createFromFormat('Y/m/d H:i', $schedule['date'] . ' ' . $schedule['start']);
    $end = DateTime::createFromFormat('Y/m/d H:i', $schedule['date'] . ' ' . $schedule['end']);
    $hours = $end->diff($start)->h;
    return $total + $hours;
});
// 25
```

### filter($func = null)

[](#filterfunc--null)

Return a new Collection containing the elements for which `$func` returns `true`. If `$func` is not passed to `filter` then only truthy values contained in the original collection will be present in the result.

#### Parameters

[](#parameters-3)

 `$func` The filter function for which each element of the collection is passed through. `$func` returns `true` if the element should be kept and `false` if not. #### Example

[](#example-3)

```
$workSchedule = new Collection([
     ['date' => '2015/04/20', 'start' => '08:00', 'end' => '12:00'],
     ['date' => '2015/04/21', 'start' => '12:00', 'end' => '17:00'],
     ['date' => '2015/04/23', 'start' => '08:00', 'end' => '17:00'],
     ['date' => '2015/04/24', 'start' => '10:00', 'end' => '15:00']
]);

$packALunch = $workSchedule->filter(function($schedule) {
    $start = DateTime::createFromFormat('Y/m/d H:i', $schedule['date'] . ' ' . $schedule['start']);
    $end = DateTime::createFromFormat('Y/m/d H:i', $schedule['date'] . ' ' . $schedule['end']);
    $hours = $end->diff($start)->h;
    return $hours > 4;
});
// object(Collection)(
     ['date' => '2015/04/21', 'start' => '12:00', 'end' => '17:00'],
     ['date' => '2015/04/23', 'start' => '08:00', 'end' => '17:00'],
     ['date' => '2015/04/24', 'start' => '10:00', 'end' => '15:00']
)
```

### slice($offset, $length = null)

[](#sliceoffset-length--null)

### flatten($flattenWith = null)

[](#flattenflattenwith--null)

Transform a multi-dimensional collection into a one dimensional collection. The responsibilty of `$flattenWith` is to accept an element of the collection and return an arrray (or an object that implements both [Countable](countable) and [ArrayAccess](arrayaccess)) of the elements contained within that element. If a `flattenWith` function is not provided to `flatten` then the method will attempt to flatten the collection using a generic `flattenWith` function, this is useful for flattening a 2 dimensional collection.

#### Parameters

[](#parameters-4)

 `$func` This function is used to flatten individual elements into single dimensional array. #### Example

[](#example-4)

### contains($value)

[](#containsvalue)

### first($matching = null)

[](#firstmatching--null)

### last($matching = null)

[](#lastmatching--null)

### reverse()

[](#reverse)

### groupBy($getGroupKey)

[](#groupbygetgroupkey)

### prepend($elem)

[](#prependelem)

### append($elem)

[](#appendelem)

### push($elem)

[](#pushelem)

### pop()

[](#pop)

### toArray()

[](#toarray)

### count()

[](#count)

Author
------

[](#author)

Colin DeCarlo,

License
-------

[](#license)

Collection is licensed under the MIT License - see the LICENSE file for details

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity11

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity56

Maturing project, gaining track record

 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

Unknown

Total

1

Last Release

3925d ago

### Community

Maintainers

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

---

Top Contributors

[![colindecarlo](https://avatars.githubusercontent.com/u/682860?v=4)](https://github.com/colindecarlo "colindecarlo (69 commits)")

---

Tags

arrayutilityiteratorcollectionfunctional

###  Code Quality

TestsPHPUnit

### Embed Badge

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

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

###  Alternatives

[nette/utils

🛠 Nette Utils: lightweight utilities for string &amp; array manipulation, image handling, safe JSON encoding/decoding, validation, slug or strong password generating etc.

2.1k394.3M1.5k](/packages/nette-utils)[athari/yalinqo

YaLinqo, a LINQ-to-objects library for PHP

4561.2M5](/packages/athari-yalinqo)[nikic/iter

Iteration primitives using generators

1.1k5.9M38](/packages/nikic-iter)[aimeos/map

Easy and elegant handling of PHP arrays as array-like collection objects similar to jQuery and Laravel Collections

4.2k412.9k11](/packages/aimeos-map)[voku/arrayy

Array manipulation library for PHP, called Arrayy!

4875.5M16](/packages/voku-arrayy)[loophp/collection

A (memory) friendly, easy, lazy and modular collection class.

745663.8k13](/packages/loophp-collection)

PHPackages © 2026

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