The Collection class provides a fluent, convenient wrapper for working with arrays of data. It offers various methods for manipulating, filtering, mapping, and extracting information from arrays.
You can create a new collection in two ways:
use Avmg\PhpSimpleUtilities\Collection;
// Using the constructor
$collection = new Collection(['apple', 'banana', 'orange']);
// Using the static factory method
$collection = Collection::collect(['apple', 'banana', 'orange']);- constructor() - make a new collection instance with an array of items.
- collect() - make a new collection instance statically.
- each() - apply a callback function to each item in the collection.
- count() - count the number of items in the collection.
- push() - add an item to the end of the collection.
- first() - retrieve the first item.
- last() - retrieve the last item.
- take() - create a new collection with a specified number of items from the start.
- get() - retrieve the item at a given key.
- put() - set the item at a given key.
- sum() - Get the sum of the given values.
- unique() - retrieve all unique items in the collection.
- isEmpty() - determine if the collection is empty.
- isNotEmpty() - determine if the collection is not empty.
- values() - get the values of the collection.
- reduce() - reduce the collection to a single value.
- map() - apply a callback to each item in the collection and return a new collection of the results.
- mapWithKeys() - apply a callback to each item in the collection and return a new collection with the keys and values swapped.
- dot() - flatten a multi-dimensional collection into a single level using 'dot' notation for keys.
- pipe() - pass the collection to a given closure and return the result.
- pipeThrough() - pass the collection to a given callback and return the result.
- tap() - apply a given callback to the collection without affecting the collection itself.
- all() - retrieve all items in the collection.
- filter() - filter the collection using a callback function.
- transform() - transform each item in the collection using a callback.
- chunk() - split the collection into chunks of the given size.
- pluck() - get the values of a specified key from the collection.
- flatten() - flatten a multi-dimensional collection into a single level.
- reject() - filter the collection by removing items that pass the truth test.
- merge() - merge another array or collection with the original collection.
- ensure() - verify that all elements of a collection are of a given type or list of types.
- contains() - determine if an item exists in the collection.
- where() - filter items by key value pair or callback.
- toArray() - convert the collection into a plain PHP array.
- toJson() - convert the collection into a JSON string.
Get all items in the collection:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$all = $collection->all();
// ['name' => 'John', 'age' => 30]Count the number of items in the collection:
$collection = Collection::collect(['apple', 'banana', 'orange']);
$count = $collection->count();
// 3Determine if the collection is empty:
$collection = Collection::collect([]);
$empty = $collection->isEmpty();
// trueDetermine if the collection is not empty:
$collection = Collection::collect(['apple', 'banana']);
$notEmpty = $collection->isNotEmpty();
// trueGet an item at a specified key:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$name = $collection->get('name');
// 'John'
// Provide a default value if the key doesn't exist
$height = $collection->get('height', 175);
// 175Get the first item in the collection:
$collection = Collection::collect(['apple', 'banana', 'orange']);
$first = $collection->first();
// 'apple'
// With a callback
$first = $collection->first(function ($item) {
return strlen($item) > 5;
});
// 'banana' (first item with more than 5 characters)
// With a default value
$first = $collection->first(function ($item) {
return strlen($item) > 10;
}, 'default');
// 'default' (no items have more than 10 characters)Get the last item in the collection:
$collection = Collection::collect(['apple', 'banana', 'orange']);
$last = $collection->last();
// 'orange'
// With a callback
$last = $collection->last(function ($item) {
return strlen($item) < 6;
});
// 'apple' (last item with fewer than 6 characters)Extract a list of values for a given key:
$collection = Collection::collect([
['product' => 'Desk', 'price' => 200],
['product' => 'Chair', 'price' => 100],
]);
$products = $collection->pluck('product');
// ['Desk', 'Chair']
// Specifying a key for the resulting collection
$prices = $collection->pluck('price', 'product');
// ['Desk' => 200, 'Chair' => 100]Get all values in the collection, discarding keys:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$values = $collection->values();
// [0 => 'John', 1 => 30]Add an item to the end of the collection:
$collection = Collection::collect(['apple', 'banana']);
$collection->push('orange');
// ['apple', 'banana', 'orange']Put an item in the collection at a specified key:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$collection->put('occupation', 'Developer');
// ['name' => 'John', 'age' => 30, 'occupation' => 'Developer']Merge another collection or array with the collection:
$collection = Collection::collect(['apple', 'banana']);
$merged = $collection->merge(['cherry', 'date']);
// ['apple', 'banana', 'cherry', 'date']Transform each item in the collection (modifies the collection):
$collection = Collection::collect([1, 2, 3]);
$collection->transform(function ($item) {
return $item * 2;
});
// [2, 4, 6]Filter items using a callback:
$collection = Collection::collect([1, 2, 3, 4, 5]);
$filtered = $collection->filter(function ($item) {
return $item > 3;
});
// [3 => 4, 4 => 5]Filter items by a key and value:
$collection = Collection::collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'Bob', 'age' => 35],
]);
// Simple equality
$johns = $collection->where('name', 'John');
// [['name' => 'John', 'age' => 30]]
// With operator
$adults = $collection->where('age', '>=', 30);
// [['name' => 'John', 'age' => 30], ['name' => 'Bob', 'age' => 35]]Remove items using a callback:
$collection = Collection::collect([1, 2, 3, 4, 5]);
$filtered = $collection->reject(function ($item) {
return $item > 3;
});
// [0 => 1, 1 => 2, 2 => 3]Get unique items from the collection:
$collection = Collection::collect([1, 1, 2, 2, 3, 3]);
$unique = $collection->unique();
// [0 => 1, 2 => 2, 4 => 3]
// With a key for object comparison
$collection = Collection::collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
['name' => 'John', 'age' => 35],
]);
$unique = $collection->unique('name');
// [0 => ['name' => 'John', 'age' => 30], 1 => ['name' => 'Jane', 'age' => 25]]Take the specified number of items:
$collection = Collection::collect([1, 2, 3, 4, 5]);
// From the beginning
$chunk = $collection->take(3);
// [1, 2, 3]
// From the end
$chunk = $collection->take(-2);
// [4, 5]Map the values into a new collection:
$collection = Collection::collect([1, 2, 3]);
$doubled = $collection->map(function ($item) {
return $item * 2;
});
// [2, 4, 6]Map with custom keys:
$collection = Collection::collect([
['name' => 'John', 'email' => 'john@example.com'],
['name' => 'Jane', 'email' => 'jane@example.com'],
]);
$keyed = $collection->mapWithKeys(function ($item) {
return [$item['email'] => $item['name']];
});
// ['john@example.com' => 'John', 'jane@example.com' => 'Jane']Flatten a multi-dimensional collection:
$collection = Collection::collect([1, [2, 3], [4, [5, 6]]]);
$flattened = $collection->flatten();
// [1, 2, 3, 4, 5, 6]
// With depth control
$flattened = $collection->flatten(1);
// [1, 2, 3, 4, [5, 6]]Flatten with "dot" notation for keys:
$collection = Collection::collect([
'user' => ['name' => 'John', 'job' => ['title' => 'Developer']]
]);
$flattened = $collection->dot();
// ['user.name' => 'John', 'user.job.title' => 'Developer']Execute a callback over each item:
$collection = Collection::collect([1, 2, 3]);
$collection->each(function ($item, $key) {
// Process each item
echo "Key: {$key}, Value: {$item}\n";
});Reduce to a single value:
$collection = Collection::collect([1, 2, 3]);
$sum = $collection->reduce(function ($carry, $item) {
return $carry + $item;
}, 0);
// 6Pass to a callback and return the result:
$collection = Collection::collect([1, 2, 3]);
$result = $collection->pipe(function ($collection) {
return $collection->sum();
});
// 6Pass through a series of callbacks:
$collection = Collection::collect([1, 2, 3]);
$result = $collection->pipeThrough([
function ($collection) {
return $collection->map(function ($item) {
return $item * 2;
});
},
function ($collection) {
return $collection->sum();
},
]);
// 12"Tap" into the collection for debugging:
$collection = Collection::collect([1, 2, 3]);
$collection->tap(function ($collection) {
// Inspect the collection without modifying it
var_dump($collection->all());
})->map(function ($item) {
return $item * 2;
});Split into chunks of the given size:
$collection = Collection::collect([1, 2, 3, 4, 5]);
$chunks = $collection->chunk(2);
// [[1, 2], [3, 4], [5]]Determine if the collection contains a value:
$collection = Collection::collect(['apple', 'banana', 'orange']);
$contains = $collection->contains('apple');
// true
// With a callback
$collection = Collection::collect([
['name' => 'John', 'age' => 30],
['name' => 'Jane', 'age' => 25],
]);
$hasAdult = $collection->contains(function ($value) {
return $value['age'] >= 30;
});
// true
// With a key-value pair
$hasJohn = $collection->contains('name', 'John');
// trueEnsure all items are of the given type(s):
$collection = Collection::collect([1, 2, 3]);
// Check for a single type
$collection->ensure('int');
// Check for multiple types
$collection->ensure(['int', 'float']);Convert the collection to an array:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$array = $collection->toArray();
// ['name' => 'John', 'age' => 30]Convert the collection to JSON:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
$json = $collection->toJson();
// '{"name":"John","age":30}'The Collection class implements the ArrayAccess interface, allowing you to interact with the collection as if it were an array:
$collection = Collection::collect(['name' => 'John', 'age' => 30]);
// Get an item
$name = $collection['name']; // 'John'
// Set an item
$collection['occupation'] = 'Developer';
// Check if an item exists
$exists = isset($collection['age']); // true
// Remove an item
unset($collection['age']);The Collection class implements the IteratorAggregate interface, allowing you to iterate over the collection using a foreach loop:
$collection = Collection::collect(['apple', 'banana', 'orange']);
foreach ($collection as $item) {
echo $item . PHP_EOL;
}