PHP Classes

PHP Collections Library: Manage collections of data values stored as arrays

Recommend this page to a friend!
  Info   View files View files (15)   DownloadInstall with Composer Download .zip   Reputation   Support forum   Blog    
Last Updated Ratings Unique User Downloads Download Rankings
2023-11-07 (2 months ago) RSS 2.0 feedNot yet rated by the usersTotal: 53 This week: 1All time: 10,536 This week: 108Up
Version License PHP version Categories
collection-classes 1.0.0MIT/X Consortium ...5PHP 5, Data types
Description 

Author

This package can manage collections of data values stored as arrays.

It provides functions to create and perform operations with collections of data values.

Currently, it can:

- Create a collection from an array of values

- Get an iterator to traverse the collection values

- Get all collection values

- Push new values to the collection

- Set, check and delete collection values

- Get the count of collection values

- Get the first or the last value of a collection

- Traverse the collection values invoking a callback function for each value

- Map, filter or reject collection values to another collection using a callback function

- Check if a value exists with a given offset

- Get the offset position of a given collection value

- Unset the collection value with a given position offset

- Get all the keys of all collection values

- Get a flat array from the collection values

- Sort the collection values with a callback function

- Create a new collection with all the collection values in reverse order

- Create a new collection with all the collection values grouped by value

Picture of Chun-Sheng, Li
  Performance   Level  
Name: Chun-Sheng, Li <contact>
Classes: 27 packages by
Country: Taiwan Taiwan
Innovation award
Innovation award
Nominee: 13x

Winner: 1x

Details

Axiom Collections

Collections is a simple and light-weight PHP collections class to help facilitate and ease the means of working with data arrays in an OOP oriented manner.

Installing Axiom Collections

Axiom Collections requires PHP 7.0 or later. It is not tested against HHVM or older (supported) versions of PHP, but there is nothing in this package (other than PHPUnit) that should cause a failure. Keep in mind that support is not guaranteed in these situations.

It is recommended that you install the package using Composer.

$ composer require axiom/collections

This package is compliant with PSR-1, PSR-2, and PSR-4. If you find any compliance oversights, please send a patch via pull request.

Using Collections

Creating Collections

You have a couple options for creating a new Collection instance.

One, by simply creating a new instance of the class directly:

$collection = new \Axiom\Collections\Collection([1, 2, 3]);

Or two, but using the make static helper method:

$collection = Collection::make([1, 2, 3]);

Methods

For the remainder of this documentation, we will run through each of the available methods provided by the Collection class. All of these methods may be chained together to fluently manipulate the underlying array of data. And lastly, in almost every case, each method will return a new Collections instance, preserving the original copy of the collection where necessary.

all()

The all method retrieves all the items from the collection.

Collection::make([1, 2, 3])->all();

// [1, 2, 3]

count()

The count method returns the total number of items in the collection:

$collection = Collection::make([1, 2, 3, 4]);

$collection->count();

// 4

each()

The each method iterates over the items in the collection and passes each item through a callback:

$collection = $collection->each(function($item, $key) {
    //
});

To stop iterating over the items and break out of the loop, simply return false from your callback:

$collection = $collection->each(function($item, $key) {
    if ($someCondition === true) {
        return false;
    }
});

exists()

The exists method determines if the given key exists in the collection.

$collection = Collection::make(['bot_id' => 1, 'name' => 'Loki']);

$collection->exists('name');

// true

filter()

The filter method filters the collection using the given callback, keeping only those items that pass a given truth test:

$collection = Collection::make([1, 2, 3, 4]);

$filtered = $collection->filter(function($item, $key) {
    return $value > 2;
});

$filtered->all();

// [3, 4]

For the inverse of filter, see the reject method.

first()

The first method returns the first element in the collection.

Collection::make([1, 2, 3, 4])->first();

// 1

flatten()

The flatten method returns a new Collection instance containing a flattened array of items.

$collection = Collection::make([
    'name' => 'Kai',
    'profile' => [
        'age' => 28,
        'favorite_games' => ['Mass Effect', 'Oxygen Not Included', 'event[0]']
    ]
]);

$result = $collection->flatten();

$result->all();

// ['Kai', 28, 'Mass Effect', 'Oxygen Not Included', 'event[0]']

get()

The get method returns the item at a given key.

$collection = Collection::make(['foo' => 'bar', 'lorem' => 'ipsum']);

$result = $collection->get('lorem');

// ipsum

groupBy()

The groupBy method returns a new Collection instance of items grouped an associative array using a callback.

$collection = Collection::make([
    'foo' => ['type' => 'foobar'],
    'bar' => ['type' => 'foobar'],
    'lorem' => ['type' => 'lorem ipsum'],
    'ipsum' => ['type' => 'lorem ipsum']
]);

$result = $collection->groupBy(function($item) {
    return $item['type'];
});

$result->all();

//
[
    'foobar' => [
        'foo' => ['type' => 'foobar'],
        'bar' => ['type' => 'foobar'],
    ],
    'lorem ipsum' => [
        'lorem' => ['type' => 'lorem ipsum'],
        'ipsum' => ['type' => 'lorem ipsum']
    ]
]

keys()

The keys method returns a new Collection instance containing all the keys of the collection items.

$collection = Collection::make(['foo' => 'bar', 'lorem' => 'ipsum']);

$result = $collection->keys();

$result->all();

// ['foo', 'lorem']

last()

The last method returns the last element in the collection.

Collection::make([1, 2, 3, 4])->last();

// 4

map()

The map method iterates through the collection and passes each valye and key to the given callback. The callback is free to modify the item and return it, thus forming a new collection of modified items:

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

$multiplied = $collection->map(function($item, $key) {
    return $item * 2;
});

$multiplied->all();

// [2, 4, 6, 8, 10]

push()

the push method appends an item to the end of the collection.

$collection = Collection::make([1, 2, 3, 4]);

$collection->push(5);

$collection->all();

// [1, 2, 3, 4, 5]

put()

The put method sets the given key and value in the collection.

$collection = Collection::make(['bot_id' => 1, 'name' => 'Odin']);

$collection->put('name', 'Loki');

$collection->all();

// ['bot_id' => 1, 'name' => 'Loki']

reject()

The reject method filters the collection using the given callback. The callback should return true is the items should be removed from the resulting collection.

$collection = Collection::make([1, 2, 3, 4]);

$filtered = $collection->reject(function($item, $key) {
    return $value > 2;
});

$filtered->all();

// [1, 2]

remove()

The remove method removes an item rom the collection by its key.

$collection = Collection::make([0, 1, 2, 3]);

$collection->remove(0);

$collection->all();

// [1, 2, 3]

reverse()

The reverse method reverses the collection items.

$collection = Collection::make([4, 1, 2, 3, 5])->reverse()->values()->all();

// [5, 3, 2, 1, 4]

$collection = Collection::make([4, 1, 2, 3, 5])->sort()->reverse()->values()->all();

// [5, 4, 3, 2, 1]

sort()

The sort method sorts the collection of items by their values in ascending order or optionally through a user-defined comparison function.

$data = [4, 1, 2, 3, 5];

$collection = Collection::make($data)->sort()->values()->all();

// [1, 2, 3, 4, 5]

$collection = Collection::make($data)->sort(function($a, $b) {
    if ($a === $b) {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
})->values()->all();

// [1, 2, 3, 4, 5]

sortByKey()

The sortByKey method sorts the collection of items by their keys in ascending order or optionally through a user-defined comparison function.

$data = [
    'foo4' => 1,
    'foo2' => 2,
    'foo5' => 3,
    'foo3' => 4,
    'foo1' => 5
];

$collection = Collection::make($data)->sortByKey()->values()->all();

// [5, 2, 4, 1, 3]

$collection = Collection::make($data)->sortByKey(function($a, $b) {
    if ($a === $b) {
        return 0;
    }

    return ($a < $b) ? -1 : 1;
})->values()->all();

// [5, 2, 4, 1, 3]

values()

The values method returns a new Collection instance containing all the values of the collection items.

$collection = Collection::make(['foo' => 'bar', 'lorem' => 'ipsum']);

$result = $collection->values();

$result->all();

// ['bar', 'ipsum']

  Files folder image Files  
File Role Description
Files folder imagesrc (1 file, 2 directories)
Files folder imagetests (1 file)
Accessible without login Plain text file .travis.yml Data Auxiliary data
Accessible without login Plain text file composer.json Data Auxiliary data
Accessible without login Plain text file composer.lock Data Auxiliary data
Accessible without login Image file failed.png Icon Icon image
Accessible without login Plain text file gulpfile.js Data Auxiliary data
Accessible without login Plain text file LICENSE Lic. License text
Accessible without login Plain text file package.json Data Auxiliary data
Accessible without login Plain text file phpunit.xml Data Auxiliary data
Accessible without login Plain text file README.md Doc. Documentation
Accessible without login Image file success.png Icon Icon image
Accessible without login Plain text file yarn.lock Data Auxiliary data

  Files folder image Files  /  src  
File Role Description
Files folder imageContracts (1 file)
Files folder imageSupport (1 file)
  Plain text file Collection.php Class Class source

  Files folder image Files  /  src  /  Contracts  
File Role Description
  Plain text file Collection.php Class Class source

  Files folder image Files  /  src  /  Support  
File Role Description
  Plain text file Arr.php Class Class source

  Files folder image Files  /  tests  
File Role Description
  Plain text file CollectionTest.php Class Class source

 Version Control Unique User Downloads Download Rankings  
 100%
Total:53
This week:1
All time:10,536
This week:108Up