This package was created to provide simple way to manipulate arrays in PHP

Overview

PHP Collections

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

Installation

composer require mleczek/collections

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

addFirst

Add item at the beginning of the collection.

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

addLast

Add item at the end of the collection.

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

avg

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

$avg = collection([1, 2, 6])->avg();
$items = [
    ['value' => 3],
    ['value' => 7],
];

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

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

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);

count

The total number of items in the collection.

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

each

Iterate over each item.

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

firstKey

Get first item key.

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

first

Get first item value.

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

flatten

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

E.g. Flattening the [[1, 2], [3]] array will output [1, 2, 3].

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

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']);

has

Check whether collection has items which match given closure.

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

isAssociative

Check whether collection is an associative array.

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

See also isIndexed method.

isEmpty

Check whether collection has zero items.

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

isIndexed

Check whether collection is an indexed array.

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

See also isAssociative method.

isNotEmpty

Check whether collection has any item.

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

join

Join all items with given glue.

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

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']);

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

keys

Returns all of the collection's keys.

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

lastKey

Get last item key.

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

last

Get last item value.

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

map

Iterates through the collection and modify each item.

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

Array keys are preserved.

max

Get maximum value from items.

The ">" operator is used to find maximum value.

$max = collection([1, 4, 7])->max();
$items = [
    ['value' => 3],
    ['value' => 7],
];

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

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]);
$first = collection([1, 2]);
$second = collection(['a' => 1, 'b' => 2]);

$collection = $first->merge($second);

min

Get minimum value from items.

The "<" operator is used to find minimum value.

$max = collection([1, 4, 7])->min();
$items = [
    ['value' => 3],
    ['value' => 7],
];

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

randomKey

Get random key from collection.

Returns null if collection is empty.

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

random

Get random item value.

Returns null if collection is empty.

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

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);

removeFirst

Remove first N items from collection.

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

removeLast

Remove last N items from collection.

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

reverse

Reverse items order.

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

skip

Skip N first items.

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

sortDesc

Sort items descending.

Strings are sorted in case insensitive manner.

$collection = collection([1, 8, 4])->sortDesc();
$items = [
    ['value' => 3],
    ['value' => 7],
];

$collection = collection($items)
    ->sortDesc(fn($item) => $item['value']);

See also sort method.

sort

Sort items ascending.

Strings are sorted in case insensitive manner.

$collection = collection([1, 8, 4])->sort();
$items = [
    ['value' => 3],
    ['value' => 7],
];

$collection = collection($items)
    ->sort(fn($item) => $item['value']);

See also sortDesc method.

sum

Returns the sum of all items in the collection.

$sum = collection([1, 2, 6])->sum();
$items = [
    ['value' => 3],
    ['value' => 7],
];

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

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

take

Take N first items.

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

toArray

Returns collection's items.

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

unique

Left only items with unique value.

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

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

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

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

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]);

where

Return collection with items which match given criteria.

$collection = collection([8, 4, 2])
    ->where(fn($item, $key) => $item > 3);
Releases(v1.0.0)
Owner
Wojciech Mleczek
Wojciech Mleczek
A redacted PHP port of Underscore.js with additional functions and goodies – Available for Composer and Laravel

Underscore.php The PHP manipulation toolbelt First off : Underscore.php is not a PHP port of Underscore.js (well ok I mean it was at first). It's does

Emma Fabre 1.1k Jun 16, 2021
This package was created to provide simple way to manipulate arrays in PHP

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

Wojciech Mleczek 13 May 24, 2021
Collection pipeline library for PHP

Knapsack Collection pipeline library for PHP Knapsack is a collection library for PHP >= 5.6 that implements most of the sequence operations proposed

Dušan Kasan 523 May 5, 2021
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

Coduo 669 Jun 14, 2021
RMT is a handy tool to help releasing new version of your software

RMT - Release Management Tool RMT is a handy tool to help releasing new versions of your software. You can define the type of version generator you wa

Liip 430 Jun 13, 2021
[READ-ONLY] CakePHP Utility classes such as Inflector, Text, Hash, Security and Xml. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Utility Classes This library provides a range of utility classes that are used throughout the CakePHP framework What's in the toolbox? Hash A

CakePHP 108 Jun 2, 2021
A framework agnostic, multi-gateway payment processing library for PHP 5.6+

Omnipay An easy to use, consistent payment processing library for PHP Omnipay is a payment processing library for PHP. It has been designed based on i

The League of Extraordinary Packages 5.3k Jun 20, 2021
:date: The VObject library for PHP allows you to easily parse and manipulate iCalendar and vCard objects

sabre/vobject The VObject library allows you to easily parse and manipulate iCalendar and vCard objects using PHP. The goal of the VObject library is

sabre.io 498 Jun 17, 2021
A set of classes to create and manipulate HTML objects abstractions

HTMLObject HTMLObject is a set of classes to create and manipulate HTML objects abstractions. Static calls to the classes echo Element::p('text')->cla

Emma Fabre 128 Jul 13, 2020
PHP OOP interface for writing Slack Block Kit messages and modals

Slack Block Kit for PHP ?? For formatting messages and modals for Slack using their Block Kit syntax via an OOP interface ?? By Jeremy Lindblom (@jere

Slack PHP Framework 10 Jun 18, 2021
Port of the Java Content Repository (JCR) to PHP.

PHP Content Repository PHPCR This repository contains interfaces for the PHPCR standard. The JSR-283 specification defines an API for a Content Reposi

PHPCR 423 May 24, 2021
Small convention based CQRS library for PHP

LiteCQRS for PHP Small naming-convention based CQRS library for PHP (loosely based on LiteCQRS for C#) that relies on the MessageBus, Command, EventSo

Benjamin Eberlei 558 May 23, 2021
A PHP library to play with the Raspberry PI's GPIO pins

php-gpio php-gpio is a simple PHP library to play with the Raspberry PI's GPIO pins. It provides simple tools such as reading & writing to pins. [UPDA

Ronan Guilloux 265 Apr 13, 2021
Extracts information about web pages, like youtube videos, twitter statuses or blog articles.

Essence is a simple PHP library to extract media information from websites, like youtube videos, twitter statuses or blog articles. If you were alread

Essence 741 May 17, 2021