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

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

originphp/collection
====================

OriginPHP Collection

2.0.1(5y ago)15771MITPHPPHP &gt;=7.3.0CI failing

Since Oct 11Pushed 5y ago1 watchersCompare

[ Source](https://github.com/originphp/collection)[ Packagist](https://packagist.org/packages/originphp/collection)[ Docs](https://www.originphp.com)[ RSS](/packages/originphp-collection/feed)WikiDiscussions master Synced 3d ago

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

Collection
==========

[](#collection)

[![license](https://camo.githubusercontent.com/6fdb99389fe9d9e8a5c197002a191ace7c8b12a2020c0fa5756cf17aa08a4966/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874477265656e2e737667)](https://camo.githubusercontent.com/6fdb99389fe9d9e8a5c197002a191ace7c8b12a2020c0fa5756cf17aa08a4966/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874477265656e2e737667)[![build](https://github.com/originphp/collection/workflows/CI/badge.svg)](https://github.com/originphp/collection/actions)[![coverage](https://camo.githubusercontent.com/e5730124da3fd15abf0a7b44593ba372372c7828c4ff114b3277982f2be7a4b6/68747470733a2f2f636f766572616c6c732e696f2f7265706f732f6769746875622f6f726967696e7068702f636f6c6c656374696f6e2f62616467652e7376673f6272616e63683d6d6173746572)](https://coveralls.io/github/originphp/collection?branch=master)

You can create a `Collection` using arrays or an object which is an instance of [Traversable](https://www.php.net/manual/en/class.traversable.php).

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

[](#installation)

To install this package

```
$ composer require originphp/collection

```

Creating a Collection
---------------------

[](#creating-a-collection)

To create a collection:

```
use Origin\Collection\Collection;
$collection = new Collection($array);
```

There is also a helper function which you can use.

```
$collection = collection($array);
```

Collections
-----------

[](#collections)

After you have finished manipulating the data you can use `toArray` or `toList` to convert the collection. Some methods return a boolean (e.g. every) or number (e.g median, average etc.), however most will return a new collection, which then can be chained through other methods.

Iteration Methods
-----------------

[](#iteration-methods)

### Extract

[](#extract)

Extracts a single column from a collection to create a list. You can use dot notation.

```
    $collection = collection($books);
    $authors = $collection->extract('authors.name');
    $list = $authors->toList();
```

You can also use a callback function :

```
    $collection = collection($books);
    $books = $collection->extract(function ($book) {
      return $book->name . ' written by ' . $book->author->name;
    });
    $list = $books->toList();
```

### Each

[](#each)

Go through each item of the collection. You should note that each does not modify data. If you want to modify data then use `map`.

```
    $collection = new Collection($books);
    $collection->each(function ($value, $key) {
        echo "{$key} - {$value}";
    });
```

### Map

[](#map)

This will iterate through each item in the collection and pass value through a callback which can modify the data and return it, creating a new collection in the process.

```
    $collection = new Collection([
        'a'=>1,'b'=>2,'c'=>3
        ]);

    // using a callable must return a value
    $plusOneCollection = $collection->map(function ($value, $key) {
        return $value + 1;
    });
```

### Combine

[](#combine)

Creates a new collection using keys and values.

```
    $collection = new Collection($results);
    $combined = $collection->combine('id', 'name');
    $array = $combined->toArray(); //[1=>'Tom','2'=>'James']
```

Results from combine can also be grouped by a third key.

```
    $collection = new Collection($results);
    $result => $collection->combine('id', 'name','profile');
    $array = $result->toArray(); // ['admin' => [1=>'tom',2=>'tim']]
```

### Chunk

[](#chunk)

Chunks a collection into multiple parts

```
  $collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]);
  $chunks = $collection->chunk(5);
  $array = $chunks->toArray();  // [[1,2,3,4,5],[6,7,8,9,10],[11,12]];
```

Filter Methods
--------------

[](#filter-methods)

### Filter

[](#filter)

Filters results using a callback function

```
    $collection = new Collection($books);
    $inStock = $collection->filter(function ($book) {
        return $book->in_stock ===  true;
    });
```

### Reject

[](#reject)

This is the inverse of filter.

```
    $collection = new Collection($books);
    $notInStock = $collection->reject(function ($book) {
        return $book->in_stock ===  true;
    });
```

### Every

[](#every)

Run truth tests on every item in the collection.

```
    $collection = new Collection($books);
    $allBooksInStock = $collection->every(function ($book) {
        return $book->in_stock > 0;
    });
    if($allBooksInStock){
        ...
    }
```

### Some

[](#some)

Check to see if at least one item matches the filter

```
    $collection = new Collection($books);
    $anyThingInStock = $collection->some(function ($book) {
        return $book->in_stock > 0;
    });
    if($anyThingInStock){
        ...
    }
```

Sorting
-------

[](#sorting)

### SortBy

[](#sortby)

Sorts a collection by a field or callback. To sort by a field, and you can use dot notation.

```
    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy('authors.name');
```

To sort by a callback.

```
    $collection = new Collection($books);
    $sortedCollection = $collection->sortBy(function ($book) {
        return $book->author->name . '-' . $book->name;
    });
```

The sortBy method accepts 3 arguments, with the first argument being the path or a callback.

The second argument is the direction,which can be either `SORT_DESC` or `SORT_ASC`.

The third argument depends upon the data and the same flags used by [PHP Sort](http://php.net/manual/en/function.sort.php), which include:

- `SORT_NUMERIC` - for numbers
- `SORT_STRING` - for strings
- `SORT_NATURAL` - for natural ordering

Aggregation
-----------

[](#aggregation)

### Min

[](#min)

Gets the first item with the smallest value.

```
    $collection = new Collection($authors);
    $author = $collection->min('rating');
```

To sort by a callback.

```
    $collection = new Collection($books);
    $author = $collection->min(function ($book) {
        return $book->author->score;
    });
```

### Max

[](#max)

Gets the first item with the smallest value.

```
    $collection = new Collection($books);
    $author = $collection->max('authors.rating');
```

To sort by a callback.

```
    $collection = new Collection($books);
    $author = $collection->max(function ($book) {
        return $book->author->score;
    });
```

Counting
--------

[](#counting)

### SumOf

[](#sumof)

Gets the sum from a field or callback.

```
    $collection = new Collection($books);
    $inStock = $collection->sumOf('in_stock');
```

To get the sum using a callback

```
    $collection = new Collection($books);
    $points = $collection->sumOf(function ($book) {
        return $book->author->rating;
    });
```

### Avg

[](#avg)

Gets the average value from a field or callback.

```
    $collection = new Collection($books);
    $avgRating = $collection->avg('authors.rating');
```

To get the average value using a callback

```
    $collection = new Collection($books);
    $avgRating = $collection->avg(function ($book) {
        return $book->author->rating;
    });
```

### Median

[](#median)

Gets the median value from a field or callback.

```
    $collection = new Collection($books);
    $median = $collection->median('authors.rating');
```

To get the median value using a callback

```
    $collection = new Collection($books);
    $median = $collection->median(function ($book) {
        return $book->author->rating;
    });
```

### Count

[](#count)

This a function to count items in the collection, it is useful when working with other collection methods such as take or chunk.

```
    $collection = new Collection($books);
    $count = $collection->count();
```

### CountBy

[](#countby)

Counts by a field and value, and results are grouped.

```
    $collection = new Collection($books);
    $counts = $collection->countBy('authors.type'); // ['famous'=>10,'new'=>20]
```

You can also use a callback.

```
    // ['odd'=>2,'even'=>3]
    $collection = new Collection($books);
    $counts = $collection->countBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    });
```

Grouping
--------

[](#grouping)

### GroupBy

[](#groupby)

Groups results by a field or callback.

```
    $collection = new Collection($books);
    $grouped = $collection->groupBy('authors.type');
    $array = $grouped->toArray();
```

You can also use a callback.

```
    $collection = new Collection($books);
    $grouped = $collection->groupBy(function ($book) {
        return $book->id % 2 == 0 ? 'even' : 'odd';
    });
    $array = $grouped->toArray();
```

Inserting Data
--------------

[](#inserting-data)

### Insert

[](#insert)

Inserts a value into a path for each item in the collection.

```
    $collection = new Collection($books);
    $newCollection = $collection->insert('authors.registered',true);
    $books = $newCollection->toArray();
```

Taking the same example, I will chain it using the helper function. This can be done with any method that returns a new collection.

```
    $books = collection($books)->insert('authors.registered',true)->toArray();
```

Other
-----

[](#other)

### Take

[](#take)

Take a number of items from a collection.

```
    $collection = new Collection($books);
    $firstLot = $collection->take(10);
    $secondLot = $collection->take(10,11);
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity15

Limited adoption so far

Community9

Small or concentrated contributor base

Maturity58

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

Every ~64 days

Recently: every ~32 days

Total

8

Last Release

1957d ago

Major Versions

1.2.1 → 2.0.02021-01-03

PHP version history (3 changes)1.0.0PHP ^7.2.0

1.2.1PHP &gt;=7.2.0

2.0.0PHP &gt;=7.3.0

### Community

Maintainers

![](https://www.gravatar.com/avatar/7e8a821333d9c7b7bc2ad3d164d142f65cd3912dea78033d31f76b0f19ba8a0c?d=identicon)[originphp](/maintainers/originphp)

---

Top Contributors

[![jamielsharief](https://avatars.githubusercontent.com/u/20553479?v=4)](https://github.com/jamielsharief "jamielsharief (30 commits)")

---

Tags

collectionsiteratorsarraysoriginPHP

###  Code Quality

TestsPHPUnit

Static AnalysisPHPStan

Type Coverage Yes

### Embed Badge

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

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

###  Alternatives

[doctrine/collections

PHP Doctrine Collections library that adds additional functionality on top of PHP arrays.

6.0k411.1M1.2k](/packages/doctrine-collections)[cakephp/collection

Work easily with arrays and iterators by having a battery of utility traversal methods

899.9M10](/packages/cakephp-collection)[ilya/belt

A handful of tools for PHP developers.

71020.8k1](/packages/ilya-belt)[dusank/knapsack

Collection library for PHP

5351.0M25](/packages/dusank-knapsack)[loophp/iterators

The missing PHP iterators.

38463.7k3](/packages/loophp-iterators)[rotexsoft/versatile-collections

A collection package that can be extended to implement things such as a Dependency Injection Container, RecordSet objects for housing database records, a bag of http cookies, or technically any collection of items that can be looped over and whose items can each be accessed using array-access syntax or object property syntax.

186.0k1](/packages/rotexsoft-versatile-collections)

PHPackages © 2026

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