A PHP library for representing and manipulating collections.
eslam-dev/collection
is a powerful PHP library for managing and manipulating collections. It provides an elegant API for working with arrays and objects, featuring advanced filtering, mapping, grouping, and transformation methods.
Install the package using Composer:
composer require eslam-dev/collection
The collect
helper creates a new instance of the EslamDev\Collection
class for the given array:
$collect = collect([
['id' => 1, 'name' => 'admin', 'type' => 'admin'],
['id' => 2, 'name' => 'admin 2', 'type' => 'admin'],
['id' => 3, 'name' => 'admin 3', 'type' => 'admin'],
['id' => 4, 'name' => 'admin 4', 'type' => 'admin'],
['id' => 5, 'name' => 'user 1', 'type' => 'user'],
]);
Merge additional items into the collection:
$collect->merge([
['id' => 8, 'name' => 'user 4', 'type' => 'user'],
['id' => 9, 'name' => 'user 5', 'type' => 'user'],
]);
Add a single item to the collection:
$collect->add(['id' => 10, 'name' => 'user 6', 'type' => 'user']);
Count the total number of items in the collection:
$collect->count();
Filter the collection by a specific key-value pair:
$collect->where('type', 'user');
Filter items using a pattern. You can use %
as a wildcard:
$collect->like('type', 'user');
// Supports array patterns
$collect->like('type', ['user', 'admin']);
Filter items where the key matches any value in an array:
$collect->whereIn('id', [1, 2, 3, 4]);
Filter items where the key does not match any value in an array:
$collect->whereNotIn('id', [5, 3, 7]);
Sort the collection by a specific key and direction:
$collect->orderBy('id', 'desc');
Get the first item in the collection:
$collect->first();
Convert the collection into an array:
$collect->toArray();
Convert the collection into an object:
$collect->toObject();
The eslam-dev/collection
library is licensed under the MIT License. See the LICENSE
file for details.
This library is developed and maintained by Eslam El Sherif.