This PHP extension provides a set of useful functional-style operations on PHP arrays, which makes array manipulation simple and scalable.
Method names and functionalities are inspired by Kotlin.Collections.
- Requires PHP 7.1 and above.
- Thread safety:
- Distinct objects: safe.
- Shared objects: unsafe.
See stubs directory for signature of all classes and methods of this extension, with PHPDoc. They can also serve as IDE helper.
The Collection
class implements ArrayAccess
and Countable
interface internally, you can treat an instance of Collection
as an ArrayObject
.
- The
isset()
,unset()
keywords can be used on elements ofCollection
. - Elements can be accessed via property and bracket expression.
empty()
,count()
can be used on instance ofCollection
.- Elements can be traversed via
foreach()
keyword.
- The
Collection::xxxTo()
methods will preserve the original key-value pairs of destinationCollection
when keys collide. - Some methods of
Collection
involves comparing two of its elements, which accepts$flags
as one of its arguments. When these methods are being invoked, make sure all elements are of the same type (numeric/string/others), otherwise you're likely to get a segfault.
Here is a simple example for how to work with arrays gracefully using this extension.
$employees = [
['name' => 'Alice', 'sex' => 'female', 'age' => 35],
['name' => 'Bob', 'sex' => 'male', 'age' => 29],
['name' => 'David', 'sex' => 'male', 'age' => 40],
['name' => 'Benjamin', 'sex' => 'male', 'age' => 32]
];
// Trying to get an array of names of male employees,
// sorted by the descending order of their age.
$names = Collection::init($employees)
->filter(function ($value) {
return $value['sex'] == 'male';
})
->sortedByDescending(function ($value) {
return $value['age'];
})
->map(function ($value) {
return $value['name'];
})
->toArray();
// You got $names == ['David', 'Benjamin', 'Bob'].