Collections
The Collection library provides a powerful and flexible implementation for working with arrays in PHP. It introduces a rich set of utility functions that help developers manipulate, transform, and manage array-based data structures more efficiently.
Since almost everything in PHP can be represented as an array, handling complex data operations can become challenging,
especially when relying heavily on the built-in array_*() family of functions such as
array_map() and array_filter().
SigmaPHP-Collections solves this problem by providing a dedicated Collection data structure that enables developers to work with arrays using a clean object-oriented approach. It supports fluent method chaining and provides powerful operations such as mapping, filtering, grouping, chunking, and iteration without requiring repetitive manual logic.
Supported Data Types
The Collection class supports all common PHP array structures and can contain:
- Numeric arrays
- Associative arrays
- Arrays of objects
- Arrays of nested collections
Mutability Behavior
By default, Collection is mutable, meaning most operations will modify the underlying collection directly.
However, the following methods are immutable and will always return a new Collection instance without modifying the original collection:
wherechunkgroupBypluckdiffreverseflattenpartitionzipuniquemapfilterslice
Keep this behavior in mind when working with collections to ensure predictable results and avoid unintended mutations.
Basic Usage Example
The following example shows the basic usage of the Collection class and its available operations.
<?php
use SigmaPHP\Collections\Collection;
$products = new Collection([
[
'name' => 'Laptop',
'price' => 1200,
'discount' => 200,
],
[
'name' => 'Phone',
'price' => 800,
'discount' => 0,
],
[
'name' => 'Tablet',
'price' => 600,
'discount' => 100,
],
]);
$discountedProducts = $products
->filter(function ($product) {
return $product['discount'] > 0;
})
->map(function ($product) {
$product['price'] -= $product['discount'];
return $product;
});
Available Methods
You can find below the complete list of available methods, along with an example for each one.all
Returns all items stored inside the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->all();
print_r($result);
/*
Array
(
[0] => apple
[1] => banana
[2] => orange
)
*/
count
Returns the total number of elements stored inside the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->count();
var_dump($result);
// int(3)
get
Retrieves an item from the collection using a specific key.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => '15'
]);
$result = $collection->get('name');
var_dump($result);
// string(7) "Ahmed"
take
Returns a specific number of items from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange',
'grape'
]);
$result = $collection->take(2);
print_r($result);
/*
Array
(
[0] => apple
[1] => banana
)
*/
first
Returns the first item from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->first();
var_dump($result);
// string(5) "apple"
last
Returns the last item from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->last();
var_dump($result);
// string(6) "orange"
set
Assigns a value to the collection using the provided key.
<?php
$collection = new Collection([]);
$collection->set('name', 'Ahmed');
$result = $collection->all();
print_r($result);
/*
Array
(
[name] => Ahmed
)
*/
has
Checks whether a specific value exists inside the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->has('banana');
var_dump($result);
// bool(true)
hasKey
Checks whether a specific key exists inside the collection.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => '15'
]);
$result = $collection->hasKey('age');
var_dump($result);
// bool(true)
keys
Returns all keys stored inside the collection.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => '15'
]);
$result = $collection->keys();
print_r($result);
/*
Array
(
[0] => name
[1] => age
)
*/
values
Returns all values stored inside the collection.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => '15'
]);
$result = $collection->values();
print_r($result);
/*
Array
(
[0] => Ahmed
[1] => 15
)
*/
remove
Removes an item from the collection using a specific key.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => '15'
]);
$collection->remove('age');
$result = $collection->all();
print_r($result);
/*
Array
(
[name] => Ahmed
)
*/
clear
Removes all items from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$collection->clear();
$result = $collection->all();
print_r($result);
/*
Array
(
)
*/
every
Checks whether all items in the collection satisfy a given condition.
<?php
$collection = new Collection([
2,
4,
6
]);
$result = $collection->every(function ($item, $key) {
return $item % 2 === 0;
});
var_dump($result);
// bool(true)
contains
Checks whether at least one item in the collection satisfies a given condition.
<?php
$collection = new Collection([
1,
3,
5,
8
]);
$result = $collection->contains(function ($item, $key) {
return $item % 2 === 0;
});
var_dump($result);
// bool(true)
partition
Splits the collection into two groups based on a given condition.
<?php
$collection = new Collection([
1,
2,
3,
4,
5
]);
$result = $collection->partition(function ($item, $key) {
return $item % 2 === 0;
});
print_r($result[0]->all());
print_r($result[1]->all());
/*
Array
(
[1] => 2
[3] => 4
)
Array
(
[0] => 1
[2] => 3
[4] => 5
)
*/
where
Returns all items that match a specific condition using a comparison operator.
Supported operators:
=!=><>=<====!==
<?php
$collection = new Collection([
[
'name' => 'Ahmed',
'age' => 25
],
[
'name' => 'John',
'age' => 30
],
[
'name' => 'Ali',
'age' => 20
]
]);
$result = $collection->where('age', '>=', 25);
print_r($result->all());
/*
Array
(
[0] => Array
(
[name] => Ahmed
[age] => 25
)
[1] => Array
(
[name] => John
[age] => 30
)
)
*/
push
Adds a new item to the end of the collection.
<?php
$collection = new Collection([
'apple',
'banana'
]);
$collection->push('orange');
$result = $collection->all();
print_r($result);
/*
Array
(
[0] => apple
[1] => banana
[2] => orange
)
*/
pop
Removes the last item from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$collection->pop();
$result = $collection->all();
print_r($result);
/*
Array
(
[0] => apple
[1] => banana
)
*/
unique
Returns a new collection containing only unique items.
<?php
$collection = new Collection([
'apple',
'banana',
'apple',
'orange'
]);
$result = $collection->unique();
print_r($result->all());
/*
Array
(
[0] => apple
[1] => banana
[3] => orange
)
*/
orderBy
Orders the items stored inside the collection.
<?php
$collection = new Collection([
30,
10,
20
]);
$collection->orderBy();
$result = $collection->all();
print_r($result);
/*
Array
(
[1] => 10
[2] => 20
[0] => 30
)
*/
sort
Sorts the collection using a custom comparison callback.
<?php
$collection = new Collection([
'banana',
'apple',
'orange'
]);
$collection->sort(function ($a, $b) {
return strlen($a) <=> strlen($b);
});
$result = $collection->all();
print_r($result);
/*
Array
(
[1] => apple
[0] => banana
[2] => orange
)
*/
map
Applies a transformation callback to every item in the collection.
<?php
$collection = new Collection([
1,
2,
3
]);
$result = $collection->map(function ($item) {
return $item * 10;
});
print_r($result->all());
/*
Array
(
[0] => 10
[1] => 20
[2] => 30
)
*/
filter
Filters collection items using a custom callback function.
<?php
$collection = new Collection([
1,
2,
3,
4,
5
]);
$result = $collection->filter(function ($item) {
return $item % 2 === 0;
});
print_r($result->all());
/*
Array
(
[1] => 2
[3] => 4
)
*/
reduce
Reduces all items in the collection into a single final value.
<?php
$collection = new Collection([
10,
20,
30
]);
$result = $collection->reduce(function ($acc, $item) {
return $acc + $item;
});
var_dump($result);
// int(60)
merge
Adds multiple items into the collection.
<?php
$collection = new Collection([
'name' => 'Ahmed'
]);
$collection->merge([
'age' => 15
]);
$result = $collection->all();
print_r($result);
/*
Array
(
[name] => Ahmed
[age] => 15
)
*/
shuffle
Randomly changes the order of items inside the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$collection->shuffle();
$result = $collection->all();
print_r($result);
/*
Example output:
Array
(
[0] => orange
[1] => apple
[2] => banana
)
*/
toJson
Converts the collection into a JSON formatted string.
<?php
$collection = new Collection([
'name' => 'Ahmed',
'age' => 15
]);
$result = $collection->toJson();
echo $result;
// {"name":"Ahmed","age":15}
slice
Returns a portion of the collection starting from the specified position.
<?php
$collection = new Collection([
'apple',
'banana',
'orange',
'grape'
]);
$result = $collection->slice(1, 2);
print_r($result->all());
/*
Array
(
[1] => banana
[2] => orange
)
*/
range
Creates a new collection containing integer values between the specified start and end values.
<?php
$collection = new Collection();
$result = $collection->range(1, 5);
print_r($result->all());
/*
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
)
*/
times
Creates a new collection containing a specific number of generated items.
<?php
$collection = new Collection();
$result = $collection->times(5, function ($index) {
return $index * 10;
});
print_r($result->all());
/*
Array
(
[0] => 0
[1] => 10
[2] => 20
[3] => 30
[4] => 40
)
*/
isEmpty
Checks whether the collection contains no items.
<?php
$collection = new Collection([]);
$result = $collection->isEmpty();
var_dump($result);
// bool(true)
isNotEmpty
Checks whether the collection contains one or more items.
<?php
$collection = new Collection([
'apple'
]);
$result = $collection->isNotEmpty();
var_dump($result);
// bool(true)
avg
Calculates and returns the average value of all items in the collection.
<?php
$collection = new Collection([
10,
20,
30
]);
$result = $collection->avg();
var_dump($result);
// float(20)
min
Returns the smallest value stored in the collection.
<?php
$collection = new Collection([
30,
10,
20
]);
$result = $collection->min();
var_dump($result);
// int(10)
max
Returns the largest value stored in the collection.
<?php
$collection = new Collection([
30,
10,
20
]);
$result = $collection->max();
var_dump($result);
// int(30)
sum
Calculates the total sum of all values inside the collection.
<?php
$collection = new Collection([
10,
20,
30
]);
$result = $collection->sum();
var_dump($result);
// int(60)
random
Returns one or more randomly selected items from the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange',
'grape'
]);
$result = $collection->random(2);
print_r($result);
/*
Example output:
Array
(
[0] => banana
[1] => grape
)
*/
chunk
Creates a new collection by dividing items into smaller groups of a specified size.
<?php
$collection = new Collection([
1,
2,
3,
4,
5
]);
$result = $collection->chunk(2);
foreach ($result->all() as $chunk) {
print_r($chunk);
}
/*
Array
(
[0] => 1
[1] => 2
)
Array
(
[0] => 3
[1] => 4
)
Array
(
[0] => 5
)
*/
each
Iterates over all items in the collection and executes the provided callback for each item.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$collection->each(function ($item) {
echo strtoupper($item) . PHP_EOL;
});
/*
APPLE
BANANA
ORANGE
*/
groupBy
Groups collection items based on a specific key.
<?php
$collection = new Collection([
['name' => 'Ahmed', 'country' => 'UAE'],
['name' => 'John', 'country' => 'USA'],
['name' => 'Ali', 'country' => 'UAE']
]);
$result = $collection->groupBy('country');
print_r($result->all());
/*
Array
(
[UAE] => Array
(
[0] => Array
(
[name] => Ahmed
[country] => UAE
)
[1] => Array
(
[name] => Ali
[country] => UAE
)
)
[USA] => Array
(
[0] => Array
(
[name] => John
[country] => USA
)
)
)
*/
pluck
Extracts all values associated with a specific key from the collection items.
<?php
$collection = new Collection([
['name' => 'Ahmed', 'country' => 'UAE'],
['name' => 'John', 'country' => 'USA'],
['name' => 'Ali', 'country' => 'UAE']
]);
$result = $collection->pluck('name');
print_r($result->all());
/*
Array
(
[0] => Ahmed
[1] => John
[2] => Ali
)
*/
diff
Returns the items that exist in the current collection but not in the given collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$compare = new Collection([
'banana'
]);
$result = $collection->diff($compare);
print_r($result->all());
/*
Array
(
[0] => apple
[2] => orange
)
*/
reverse
Returns a new collection with items in reversed order.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$reverse = $collection->reverse();
print_r($reverse->all());
/*
Array
(
[2] => orange
[1] => banana
[0] => apple
)
*/
toString
Returns the string representation of the collection.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->toString();
echo $result;
// Collection(64): 00000000000000000000000000000000
make
Creates a new collection instance using the static factory method.
<?php
$collection = Collection::make([
'apple',
'banana',
'orange'
]);
print_r($collection->all());
/*
Array
(
[0] => apple
[1] => banana
[2] => orange
)
*/
flatten
Converts a multi-dimensional collection into a single-dimensional collection.
<?php
$collection = new Collection([
[1, 2],
[3, 4],
[5, 6]
]);
$result = $collection->flatten();
print_r($result->all());
/*
Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)
*/
pad
Extends the collection by adding values until it reaches the requested size.
<?php
$collection = new Collection([
'apple',
'banana'
]);
$result = $collection->pad(5, 'unknown');
print_r($result->all());
/*
Array
(
[0] => apple
[1] => banana
[2] => unknown
[3] => unknown
[4] => unknown
)
*/
zip
Combines the collection items with another array by matching their indexes.
<?php
$collection = new Collection([
'apple',
'banana',
'orange'
]);
$result = $collection->zip([
'red',
'yellow',
'orange'
]);
print_r($result->all());
/*
Array
(
[0] => Array
(
[0] => apple
[1] => red
)
[1] => Array
(
[0] => banana
[1] => yellow
)
[2] => Array
(
[0] => orange
[1] => orange
)
)
*/