Collection is a small PHP library that provides convenient tools for handling arrays.
The current release requires PHP 8.3 or later.
Just add chindit/collection to your composer.json
composer require chindit/collection
To create a collection, pass an array to the constructor:
use Chindit\Collection\Collection;
$collection = new Collection(['a', 'b' => 'c']);
all() array : return all values of the collection, without preserving keyscontains($search) bool : check whether a value is strictly presentcount() int : return the number of elementseach($callable) Collection : apply a callback to every element; stop when it returns falsefilter($callable) Collection : return only the elements accepted by the callbackfirst() mixed : return the first elementflatten($depth = 500) Collection : flatten nested arrays and collections up to $depthget($key, $defaultValue = null) mixed : return the value for a key, or the default valuegetIterator() Traversable : provide a fresh iterator for use with foreachgroupBy($key) Collection : group elements by a field/accessor or by a callbackhas($key) bool : check whether a key existsisEmpty() bool : check whether the collection is emptyisNotEmpty() bool : check whether the collection is not emptykeyBy($key) Collection : rewrite keys using an accessor or callbackkeys() Collection : return the collection’s keysmap($callable) Collection : apply a callback to each elementmerge($collection) Collection : merge another collectionmergeRecursive($collection) Collection : recursively merge another collectionpluck($string) Collection : extract a field from every elementpush($element) Collection : append an elementput($key, $element) Collection : add an element with a specific keyrsort() Collection : sort the collection in reverse ordersort() Collection : sort the collectiontoArray() array : convert the collection, including nested collections, to an array while preserving keysunique() Collection : return the collection without duplicate values// Let's assume we have some Car objects
$myObject = new Car();
$myCollection = new Collection($arrayOfCarObjects);
// «pluck» will access «brand» property or «getBrand» method on all elements of the collection and return its value
// «unique» will remove all duplicates
$uniqueBrands = $myCollection->pluck('brand')->unique();
Collections can be iterated with foreach. A new iterator is created for
each loop:
foreach ($myCollection as $key => $value) {
// use $key and $value
}
If you have any issue or question with this repository, do not hesitate to leave a comment in the «Issue» sections ^^