PHPackages                             mleczek/collections - 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. mleczek/collections

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

mleczek/collections
===================

Easy way to manipulate arrays in PHP.

v1.0.0(5y ago)12121MITPHPPHP ~7.4 || ~8.0

Since May 1Pushed 4y ago1 watchersCompare

[ Source](https://github.com/mleczek/collections)[ Packagist](https://packagist.org/packages/mleczek/collections)[ Docs](https://github.com/mleczek/collections)[ RSS](/packages/mleczek-collections/feed)WikiDiscussions master Synced 5d ago

READMEChangelog (1)Dependencies (1)Versions (2)Used By (0)

PHP Collections
===============

[](#php-collections)

This package was created to provide simple way to manipulate arrays in PHP. The package was inspired by the Laravel Collections.

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

[](#installation)

```
composer require mleczek/collections

```

Getting started
---------------

[](#getting-started)

Convert any array to collection:

```
$collection = new \Mleczek\Collections\Collection([
    ['id' => 3, 'firstName' => 'Debra', 'lastName' => 'Barnett'],
    ['id' => 8, 'firstName' => 'Ronnie', 'lastName' => 'Coleman'],
    ['id' => 2, 'firstName' => 'Gabriel', 'lastName' => 'Adams'],
]);

// ...and perform some operations:
$names = $collection
    ->whereIn(fn($x) => $x['id'], [3, 2])
    ->map(fn($x) => $x['firstName'] .' '. $x['lastName'])
    ->join(', ');

// $names is equal "Debra Barnett, Gabriel Adams"
```

You can also do this using `collection` helper method:

```
$sum = collection([1, 2, 5])
    ->map(fn($x) => $x * 2)
    ->sum();

// $sum is equal 16 (2+4+10)
```

Available operations
--------------------

[](#available-operations)

- [addFirst](#addFirst)
- [addLast](#addLast)
- [avg](#avg)
- [chunk](#chunk)
- [count](#count)
- [each](#each)
- [firstKey](#firstKey)
- [first](#first)
- [flatten](#flatten)
- [groupBy](#groupBy)
- [has](#has)
- [isAssociative](#isAssociative)
- [isEmpty](#isEmpty)
- [isIndexed](#isIndexed)
- [isNotEmpty](#isNotEmpty)
- [join](#join)
- [keyBy](#each)
- [keys](#keys)
- [lastKey](#lastKey)
- [last](#last)
- [map](#map)
- [max](#max)
- [merge](#merge)
- [min](#min)
- [randomKey](#randomKey)
- [random](#random)
- [reduce](#reduce)
- [removeFirst](#removeFirst)
- [removeLast](#removeLast)
- [reverse](#reverse)
- [skip](#skip)
- [sortDesc](#sortDesc)
- [sort](#sort)
- [sum](#sum)
- [take](#take)
- [toArray](#toArray)
- [unique](#unique)
- [values](#values)
- [whereIn](#whereIn)
- [where](#where)

### addFirst

[](#addfirst)

Add item at the beginning of the collection.

```
$collection = collection([2, 3])->addFirst(1); // [1, 2, 3]
```

### addLast

[](#addlast)

Add item at the end of the collection.

```
$collection = collection([2, 3])->addLast(4); // [2, 3, 4]
```

### avg

[](#avg)

Calculate average value from items. Zero if there're no items in collection.

```
$avg = collection([1, 2, 6])->avg(); // 3
```

```
$items = [
    ['value' => 3],
    ['value' => 7],
];

$avg = collection($items)
    ->avg(fn($item, $key) => $item['value']); // 5
```

Throws when trying to calculate avg from non-number value.

### chunk

[](#chunk)

Breaks into multiple, smaller collections of a given size.

E.g. for chunk size 2 the output array for `[1, 2, 3]` will be `[[1, 2], [3]]`.

```
$collection = collection([1, 2, 3])->chunk(2); // [[1, 2], [3]]
```

### count

[](#count)

The total number of items in the collection.

```
$count = collection([1, 2])->count(); // 2
```

### each

[](#each)

Iterate over each item.

```
collection(['a' => 1, 'b' => 2])
    ->each(fn($item, $key) => printf("$key:$item"));
```

### firstKey

[](#firstkey)

Get first item key.

```
$key = collection(['a' => 1, 'b' => 2])->firstKey(); // 'a'
```

### first

[](#first)

Get first item value.

```
$item = collection(['a' => 1, 'b' => 2])->first(); // 1
```

### flatten

[](#flatten)

Convert array of arrays to array (remove one dimension).

```
$collection = collection([[1, 2], [3]])->flatten(); // [1, 2, 3]
```

### groupBy

[](#groupby)

Groups the collection's items by a given key.

```
$items = [
    ['brand' => 'Jeep', 'model' => 'Cherokee Latitude'],
    ['brand' => 'Nissan', 'model' => 'Sentra SV'],
    ['brand' => 'Nissan', 'model' => 'Murano Platinum'],
];

$collection = collection($items)
    ->groupBy(fn($item, $key) => $item['brand']); // ['Jeep' => [...], 'Nissan' => [...]]
```

### has

[](#has)

Check whether collection has items which match given closure.

```
$test = collection([2, 7, 3])
    ->has(fn($item, $key) => $item === 7); // true
```

### isAssociative

[](#isassociative)

Check whether collection is an associative array.

```
$test = collection([1, 4])->isAssociative(); // false
$test = collection(['a' => 1, 4])->isAssociative(); // true
```

See also [`isIndexed`](#isIndexed) method.

### isEmpty

[](#isempty)

Check whether collection has zero items.

```
$test = collection([])->isEmpty(); // true
```

### isIndexed

[](#isindexed)

Check whether collection is an indexed array.

```
$test = collection([1, 4])->isIndexed(); // true
$test = collection(['a' => 1, 4])->isIndexed(); // false
```

See also [`isAssociative`](#isAssociative) method.

### isNotEmpty

[](#isnotempty)

Check whether collection has any item.

```
$test = collection([8, 2])->isNotEmpty(); // true
```

### join

[](#join)

Join all items with given glue.

```
$string = collection(['Nissan', 'Jeep', 'Ford'])->join(', '); // 'Nissan, Jeep, Ford'
```

### keyBy

[](#keyby)

Change collection's items keys.

```
$items = [
    ['id' => 5, 'username' => 'lorraine'],
    ['id' => 1, 'username' => 'gabriel.hill'],
    ['id' => 4, 'username' => 'steward'],
];

$collection = collection($items)
    ->keyBy(fn($item, $key) => $item['id']); // [5 => [...], 1 => [...], 4 => [...]]
```

If multiple items have the same key, the exception will be thrown.

### keys

[](#keys)

Returns all of the collection's keys.

```
$array = collection(['a' => 1, 'b' => 3])->keys(); // ['a', 'b']
```

### lastKey

[](#lastkey)

Get last item key.

```
$key = collection(['a' => 1, 'b' => 2])->lastKey(); // 'b'
```

### last

[](#last)

Get last item value.

```
$item = collection(['a' => 1, 'b' => 2])->last(); // 2
```

### map

[](#map)

Iterates through the collection and modify each item.

```
$collection = collection([1, 4])
    ->map(fn($item, $key) => $item * 2); // [2, 8]
```

Array keys are preserved.

### max

[](#max)

Get maximum value from items.

The "&gt;" operator is used to find maximum value.

```
$max = collection([1, 4, 7])->max(); // 7
```

```
$items = [
    ['value' => 3],
    ['value' => 8],
];

$avg = collection($items)
    ->max(fn($item, $key) => $item['value']); // 8
```

### merge

[](#merge)

Merge collection/array to current array.

In associative arrays values for existing keys will be overwrite. In indexed arrays new values are always appended at the end of collection.

```
$collection = collection([1, 2])->merge([3, 4]); // [1, 2, 3, 4]
```

```
$first = collection([1, 2]);
$second = collection(['a' => 1, 'b' => 2]);

$collection = $first->merge($second);// [1, 2, 'a' => 1, 'b' => 2]
```

### min

[](#min)

Get minimum value from items.

The "&lt;" operator is used to find minimum value.

```
$max = collection([1, 4, 7])->min(); // 1
```

```
$items = [
    ['value' => 3],
    ['value' => 8],
];

$avg = collection($items)
    ->min(fn($item, $key) => $item['value']); // 3
```

### randomKey

[](#randomkey)

Get random key from collection.

Returns null if collection is empty.

```
$item = collection(['a' => 1, 'b' => 2])->randomKey();
```

### random

[](#random)

Get random item value.

Returns null if collection is empty.

```
$item = collection([1, 8, 4])->random();
```

### reduce

[](#reduce)

Reduces the collection to a single value, passing the result of each iteration into the subsequent iteration.

```
$initialState = 2;
$result = collection([1, 8, 4])
    ->reduce(fn($item, $state) => $state + $item, $initialState); // 15
```

### removeFirst

[](#removefirst)

Remove first N items from collection.

```
$collection = collection([1, 8, 4])->removeFirst(); // [8, 4]
$collection = collection([1, 8, 4])->removeFirst(2); // [4]
```

### removeLast

[](#removelast)

Remove last N items from collection.

```
$collection = collection([1, 8, 4])->removeLast(); // [1, 8]
$collection = collection([1, 8, 4])->removeLast(2); // [1]
```

### reverse

[](#reverse)

Reverse items order.

```
$collection = collection([1, 8, 4])->reverse(); // [4, 8, 1]
```

### skip

[](#skip)

Skip N first items.

```
$collection = collection([1, 8, 4])->skip(); // [8, 4]
$collection = collection([1, 8, 4])->skip(2); // [4]
```

### sortDesc

[](#sortdesc)

Sort items descending.

Strings are sorted in case insensitive manner.

```
$collection = collection([1, 8, 4])->sortDesc(); // [8, 4, 1]
```

```
$items = [
    ['value' => 3],
    ['value' => 7],
];

$collection = collection($items)
    ->sortDesc(fn($item) => $item['value']); // ['value' => 7, 'value' => 3]
```

See also [`sort`](#sort) method.

### sort

[](#sort)

Sort items ascending.

Strings are sorted in case insensitive manner.

```
$collection = collection([1, 8, 4])->sort(); // [1, 4, 8]
```

```
$items = [
    ['value' => 3],
    ['value' => 7],
];

$collection = collection($items)
    ->sort(fn($item) => $item['value']); // ['value' => 3, 'value' => 7]
```

See also [`sortDesc`](#sortDesc) method.

### sum

[](#sum)

Returns the sum of all items in the collection.

```
$sum = collection([1, 2, 6])->sum(); // 9
```

```
$items = [
    ['value' => 3],
    ['value' => 7],
];

$sum = collection($items)
    ->sum(fn($item, $key) => $item['value']); // 10
```

Throws when trying to calculate sum from non-number value.

### take

[](#take)

Take N first items.

```
$collection = collection([1, 8, 4])->take(); // [1]
$collection = collection([1, 8, 4])->take(2); // [1, 8]
```

### toArray

[](#toarray)

Returns collection's items.

```
$array = collection([6, 3, 1])->toArray(); // [6, 3, 1]
```

### unique

[](#unique)

Left only items with unique value.

```
$collection = collection([6, 1, 3, 1])->unique(); // [6, 1, 3]
```

First occurrence is taken if multiple same values are encountered.

```
$items = [
    ['brand' => 'Jeep', 'model' => 'Cherokee Latitude'],
    ['brand' => 'Nissan', 'model' => 'Sentra SV'],
    ['brand' => 'Nissan', 'model' => 'Murano Platinum'],
];

$collection = collection([$items])
    ->unique(fn($item, $key) => $item['brand']);
```

### values

[](#values)

Returns all of the collection's values (as indexed array).

```
$values = collection(['a' => 1, 'b' => 2])->values(); // [1, 2]
```

### whereIn

[](#wherein)

Return collection with items that needle is in haystack of accepted values.

```
$collection = collection([8, 4, 2])
    ->whereIn(fn($item, $key) => $item, [4, 7, 2]); // [4, 2]
```

### where

[](#where)

Return collection with items which match given criteria.

```
$collection = collection([8, 4, 2])
    ->where(fn($item, $key) => $item > 3); // [8, 4]
```

###  Health Score

28

—

LowBetter than 54% of packages

Maintenance20

Infrequent updates — may be unmaintained

Popularity17

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity57

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

1841d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/143e31568d2a8cef787b416fd2b5f10b78d28cb141ffe049c197d7fb31dc911c?d=identicon)[mleczek](/maintainers/mleczek)

---

Top Contributors

[![mleczek](https://avatars.githubusercontent.com/u/15350415?v=4)](https://github.com/mleczek "mleczek (3 commits)")

---

Tags

arraycollectionmanipulationarraycollectionmanipulate

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mleczek-collections/health.svg)

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

###  Alternatives

[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)[athari/yalinqo

YaLinqo, a LINQ-to-objects library for PHP

4561.2M5](/packages/athari-yalinqo)[yansongda/supports

common components

211.4M31](/packages/yansongda-supports)[armincms/json

A Laravel Nova field.

25149.4k3](/packages/armincms-json)[graze/sort

A collection of array sorting transforms and functions

12289.6k2](/packages/graze-sort)[graze/data-structure

Data collections and containers

12287.4k8](/packages/graze-data-structure)

PHPackages © 2026

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