asko/collection

A utility library for working with collections.

v1.0 2024-06-23 00:14 UTC

This package is auto-updated.

Last update: 2024-10-23 01:10:59 UTC


README

codecov

A generic class that encapsulates a collection of items and provides helper methods to work with said collection.

Installation

composer require asko/collection

Usage

Creating a new collection is as simple as creating a new Collection class instance and passing the constructor an array of items.

use Asko\Collection\Collection;

$collection = new Collection([1, 2, 3, 4, 5]);

Available methods

push

Add an item to the collection.

$collection->push(6);

filter

Filter the collection using a callback.

$collection->filter(function ($item) {
    return $item > 3;
});

map

Map over the collection using a callback.

$collection->map(function ($item) {
    return $item * 2;
});

any

Check if any item in the collection passes a truth test.

$collection->any(function ($item) {
    return $item > 3;
});

all

Check if all items in the collection pass a truth test.

$collection->all(function ($item) {
    return $item > 3;
});

each

Iterate over the collection.

$collection->each(function ($item) {
    echo $item;
});

reduce

Reduce the collection to a single value.

$collection->reduce(function ($acc, $item) {
    return $acc + $item;
}, 0);

first

Get the first item in the collection.

$collection->first();

last

Get the last item in the collection.

$collection->last();

avg

Get the average of the items in the collection by predicate

$collection->avg(function ($item) {
    return $item * 2;
});

sum

Get the sum of the items in the collection by predicate

$collection->sum(function ($item) {
    return $item * 2;
});

count

Get the number of items in the collection.

$collection->count();

toArray

Get the collection as an array.

$collection->toArray();