barogue/collection

A class wrapper for PHP native arrays

0.0.2 2023-08-27 12:09 UTC

This package is auto-updated.

Last update: 2024-11-28 16:42:45 UTC


README

Tests codecov Licence Badge Release Badge Tag Badge Issues Badge Code Size

A class wrapper for PHP native arrays

Compatibility and dependencies

This library is compatible with PHP version 8.1 and 8.2.

This library has no dependencies.

Installation

Installation is simple using composer.

composer require barogue/collections

Or simply add it to your composer.json file

{
    "require": {
        "barogue/collections": "^1.0"
    }
}

Contributing

This library follows PSR-1 & PSR-2 standards.

Unit Tests

Before pushing any changes, please ensure the unit tests are all passing.

If possible, feel free to improve coverage in a separate commit.

vendor/bin/phpunit

Code sniffer

Before pushing, please ensure you have run the code sniffer. Only run it using the lowest support PHP version (8.1)

vendor/bin/php-cs-fixer fix

Static Analyses

Before pushing, please ensure you have run the static analyses tool.

vendor/bin/phan

Benchmarks

Before pushing, please ensure you have checked the benchmarks and ensured that your code has not introduced any slowdowns.

Feel free to speed up existing code, in a separate commit.

Feel free to add more benchmarks for greater coverage, in a separate commit.

vendor/bin/phpbench run --report=speed
vendor/bin/phpbench run --report=speed --output=markdown
vendor/bin/phpbench run --report=speed --filter=benchNetFromTax --iterations=50 --revs=50000

vendor/bin/phpbench xdebug:profile
vendor/bin/phpbench xdebug:profile --gui

Documentation

This library adds a new class that can wrap around native arrays to mke interactions with them quicker and simpler.

Below you can find links to the documentation for the new features.

Creating an instance of the collection

use Barogue\Collections\Collection;

// Using the constructor
$collection = new Collection();
$collection = new Collection([1, 2, 3]);

// Using the chainable constructor
$collection = Collection::instance();
$collection = Collection::instance([1, 2, 3]);

// Create using a range
$celsius = Collection::range(0, 100);
$alphabet = Collection::range('a', 'z');
$evens = Collection::range(0, 100, 2);

Getting data from a collection

use Barogue\Collections\Collection;

// Collections can be used exactly like a normal array
$collection = new Collection([1, 2, 3]);
$collection[] = 4;
$collection['test'] = 5;
echo $collection[1]; // 2 

// Get the original array
$collection->getArray();

// Get an iterator
$collection->getIterator();

// Getting the size of the collection
echo count($collection); // 5
echo $collection->count(); // 5

A list of native methods integrated into this class

array_change_key_case Changes the case of all keys in an array

use Barogue\Collections\Collection;

$collection = new Collection(["FirSt" => 1, "SecOnd" => 4]);

$collection->changeKeyCase(CASE_UPPER); // ["FIRST" => 1, "SECOND" => 4]
$collection->changeKeyCase(CASE_LOWER); // ["first" => 1, "second" => 4]

$collection->changeKeyUpperCase(); // ["FIRST" => 1, "SECOND" => 4]
$collection->changeKeyLowerCase(); // ["first" => 1, "second" => 4]

array_chunk Split an array into chunks

use Barogue\Collections\Collection;

$collection = Collection::range(1, 100);
$chunks = $collection->chunk(10);

array_column Return the values from a single column in the input array

use Barogue\Collections\Collection;

$collection = new Collection([
    'player_1' => [
        'name' => 'John',
        'stats' => [
            'hp' => 50,
            'exp' => 1000
        ]
    ],
    'player_2' => [
        'name' => 'Jane',
        'stats' => [
            'hp' => 70,
            'exp' => 1000
        ]
    ]
]);
$hps = $collection->column('stats.hp'); // [50, 70]
$hps = $collection->column('stats.hp', 'name'); // ['John' => 50, 'Jane' => 70]

array_combine Creates an array by using one array for keys and another for its values

use Barogue\Collections\Collection;

$keys = new Collection(['a', 'b', 'c']);
$combined = $keys->combine(1, 2, 3); // ['a' => 1, 'b' => 2, 'c' => 3]


$combined = Collection::instance(['a', 'b', 'c'])->combine(1, 2, 3); // ['a' => 1, 'b' => 2, 'c' => 3]

array_count_values Counts all the values of an array

use Barogue\Collections\Collection;

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

$appearances = $collection->countValues(); // [1 => 3, 2 => 2, 3 => 1, 4 => 1, 'a' => 2]

array_diff_assoc Computes the difference of arrays with additional index check

// Add documentation

array_diff_key Computes the difference of arrays using keys for comparison

// Add documentation

array_diff_uassoc Computes the difference of arrays with additional index check which is performed by a user supplied callback function

// Add documentation

array_diff_ukey Computes the difference of arrays using a callback function on the keys for comparison

// Add documentation

array_diff Computes the difference of arrays

use Barogue\Collections\Collection;

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

array_fill_keys Fill an array with values, specifying keys

// Add documentation

array_fill Fill an array with values

// Add documentation

array_filter Filters elements of an array using a callback function

use Barogue\Collections\Collection;

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

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

array_flip Exchanges all keys with their associated values in an array

use Barogue\Collections\Collection;

$collection = new Collection(['a', 'b', 'c']);
$flipped = $collection->flip(); // ['a' => 0, 'b' => 1, 'c' => 2]

$collection = new Collection(['a', 'b', 'c', 'a']);
$flipped = $collection->flip(); // ['a' => 0, 'b' => 1, 'c' => 2]
$doubleFlipped = $collection->flip()->flip(); // ['a' => 0, 'b' => 1, 'c' => 2]

array_intersect_assoc Computes the intersection of arrays with additional index check

// Add documentation

array_intersect_key Computes the intersection of arrays using keys for comparison

// Add documentation

array_intersect_uassoc Computes the intersection of arrays with additional index check, compares indexes by a callback function

// Add documentation

array_intersect_ukey Computes the intersection of arrays using a callback function on the keys for comparison

// Add documentation

array_intersect Computes the intersection of arrays

// Add documentation

array_is_list Checks whether a given array is a list

use Barogue\Collections\Collection;

Collection::instance(['a', 'b', 'c'])->isList(); // true
Collection::instance(['a' => 1, 'b', 'c'])->isList(); // false

array_key_exists Checks if the given key or index exists in the array

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => [
        'a' => 1,
        'b' => null,
        'c' => 3,
    ],
]);
$collection->exists('a'); // true
$collection->exists('z'); // false
$collection->exists('c.a'); // true
$collection->exists('c.b'); // true
$collection->exists('c.z'); // false

array_key_first Gets the first key of an array

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4,
    'e' => 5,
]);

$collection->firstKey(); // 'a'
$collection->firstKey(fn($value, $key) => $value >= 3); // 'c'
$collection->firstKey(fn($value, $key) => $key != 'a'); // 'b'

array_key_last Gets the last key of an array

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => 3,
    'd' => 4,
    'e' => 5,
]);

$collection->lastKey(); // 'e'
$collection->lastKey(fn($value, $key) => $value >= 3); // 'e'
$collection->lastKey(fn($value, $key) => $key != 'a'); // 'e'

array_keys Return all the keys or a subset of the keys of an array

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => [
        'a' => 1,
        'b' => null,
        'c' => 3,
    ],
]);

$collection->keys(); // ['a', 'b', 'c']

$collection->keys(true); // ['a', 'b', 'c.a', 'c.b', 'c.c']

array_map Applies the callback to the elements of the given arrays

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => 3
]);

$increased = $collection->map(function ($value) {
    return $value * 2;
}); // ['a' => 2, 'b' => 4, 'c' => 6]

$concatenatedKeys = $collection->map(function ($value, $key) {
    return $key.'-'.$value;
}); // ['a' => 'a-1', 'b' => 'b-2', 'c' => 'c-3']

array_merge_recursive Merge one or more arrays recursively

// Add documentation

array_merge Merge one or more arrays

// Add documentation

array_multisort Sort multiple or multi-dimensional arrays

// Add documentation

array_pad Pad array to the specified length with a value

// Add documentation

array_pop Pop the element off the end of array

use Barogue\Collections\Collection;

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]);
$single = $collection->pop(); // 8
$multiple = $collection->pop(4)->getArray(); // [7, 6, 5, 4]

array_product Calculate the product of values in an array

// Add documentation

array_push Push one or more elements onto the end of array

use Barogue\Collections\Collection;

$collection = new Collection();
$collection->push('test'); // ['test']
$collection->push(1, 2, 3, 4, 5, 6);  // ['test', 1, 2, 3, 4, 5]

array_rand Pick one or more random keys out of an array

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => 3
]);

$collection->randomKey(); // 'b'
$collection->randomKeys(2)->getArray(); // ['c', 'a']

array_reduce Iteratively reduce the array to a single value using a callback function

use Barogue\Collections\Collection;

$factorial = Collection::range(10, 1)->reduce(fn($carry, $value) => $carry * $value, 1)
$factorial = Collection::factorial(10)

array_replace_recursive Replaces elements from passed arrays into the first array recursively

// Add documentation

array_replace Replaces elements from passed arrays into the first array

// Add documentation

array_reverse Return an array with elements in reverse order

use Barogue\Collections\Collection;

$collection = new Collection([
    'a' => 1,
    'b' => 2,
    'c' => 3
]);

$reversedCopy = $collection->reverse(); // ['c' => 3, 'b' => 2, 'a' => 1]

array_search Searches the array for a given value and returns the first corresponding key if successful

// Add documentation

array_shift Shift an element off the beginning of array

use Barogue\Collections\Collection;

$collection = new Collection([1, 2, 3, 4, 5, 6, 7, 8]);
$single = $collection->shift(); // 1
$multiple = $collection->shift(4)->getArray(); // [2, 3, 4, 5]

array_slice Extract a slice of the array

// Add documentation

array_splice Remove a portion of the array and replace it with something else

// Add documentation

array_sum Calculate the sum of values in an array

use Barogue\Collections\Collection;

$sum = Collection::instance([1, 2, 3])->sum(); // 6
$sum = Collection::range(1, 100)->sum(); // 5050

array_udiff_assoc Computes the difference of arrays with additional index check, compares data by a callback function

// Add documentation

array_udiff_uassoc Computes the difference of arrays with additional index check, compares data and indexes by a callback function

// Add documentation

array_udiff Computes the difference of arrays by using a callback function for data comparison

// Add documentation

array_uintersect_assoc Computes the intersection of arrays with additional index check, compares data by a callback function

// Add documentation

array_uintersect_uassoc Computes the intersection of arrays with additional index check, compares data and indexes by separate callback functions

// Add documentation

array_uintersect Computes the intersection of arrays, compares data by a callback function

// Add documentation

array_unique Removes duplicate values from an array

// Add documentation

array_unshift Prepend one or more elements to the beginning of an array

// Add documentation

array_values Return all the values of an array

use Barogue\Collections\Collection;

$values = Collection::instance(['a' => 1, 'b' => 2])->values()->getArray(); // [1, 2]

array_walk_recursive Apply a user function recursively to every member of an array

// Add documentation

array_walk Apply a user supplied function to every member of an array

// Add documentation

arsort Sort an array in descending order and maintain index association

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 9, 'b' => 1, 'c' => 5]);
$collection->reverseSort(); // ['a' => 9, 'c' => 5, 'b' => 1]

asort Sort an array in ascending order and maintain index association

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 9, 'b' => 5, 'c' => 1]);
$collection->sort(); // ['c' => 1, 'b' => 5, 'a' => 9]

compact Create array containing variables and their values

// Add documentation

count Counts all elements in an array or in a Countable object

use Barogue\Collections\Collection;

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

count($collection); // 3
$collection->count(); // 3

current Return the current element in an array

// Add documentation

each Return the current key and value pair from an array and advance the array cursor

// Add documentation

extract Import variables into the current symbol table from an array

// Add documentation

implode Join array elements with a string

use Barogue\Collections\Collection;
echo Collection::instance('a', 'b', 'c')->implode(', '); // "a, b, c"
echo Collection::instance('a', 'b', 'c')->implode(', ', ' and '); // "a, b and c"

in_array Checks if a value exists in an array

// Add documentation

krsort Sort an array by key in descending order

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 5, 'c' => 4, 'z' => 3, 'b' => 2, 'e' => 1]);
$sorted = $collection->sortKeys()->reverse(); // ['z' => 3, 'e' => 1, 'c' => 4, 'b' => 2, 'a' => 5]

ksort Sort an array by key in ascending order

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 5, 'c' => 4, 'z' => 3, 'b' => 2, 'e' => 1]);
$sorted = $collection->sortKeys(); // ['a' => 5, 'b' => 2, 'c' => 4, 'e' => 1, 'z' => 3]

list Assign variables as if they were an array

use Barogue\Collections\Collection;

$collection = new Collection(['coffee', 'brown', 'caffeine']);
list($drink, $color, $power) = $collection;
echo $drink; // coffee
echo $color; // brown
echo $power; // caffeine

natcasesort Sort an array using a case insensitive "natural order" algorithm

// Add documentation

natsort Sort an array using a "natural order" algorithm

// Add documentation

range Create an array containing a range of elements

use Barogue\Collections\Collection;

$numbers = Collection::range(0, 100);
$even = Collection::range(0, 100, 2);
$alphabet = Collection::range('a', 'z');

rsort Sort an array in descending order

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 9, 'b' => 1, 'c' => 5]);
$collection->reverseSort()->values(); // [9, 5, 1]

shuffle Shuffle an array

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3]);
$collection->shuffle(); // ['b' => 2, 'c' => 3, 'a' => 1]
$collection->shuffle(false); // [3, 1, 2]

sizeof Alias of count

use Barogue\Collections\Collection;

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

count($collection); // 3
$collection->count(); // 3

sort Sort an array in ascending order

use Barogue\Collections\Collection;

$collection = new Collection(['a' => 9, 'b' => 5, 'c' => 1]);
$collection->sort()->values(); // [1, 5, 9]

uasort Sort an array with a user-defined comparison function and maintain index association

use Barogue\Collections\Collection;

$collection = new Collection([5, 4, 3, 2, 1]);
$collection->sortCallback(function($a, $b) {
    $aEven = $a % 2 == 0 ? 1 : 0;
    $bEven = $b % 2 == 0 ? 1 : 0;
    return $aEven === $bEven ? $a <=> $b : $aEven <=> $bEven;
}); // [4 => 1, 2 => 3, 0 => 5, 3 => 2, 1 => 4]

uksort Sort an array by keys using a user-defined comparison function

use Barogue\Collections\Collection;

$collection = new Collection([5, 4, 3, 2, 1]);
$collection->sortCallback(function($a, $b) {
    $aEven = $a % 2 == 0 ? 1 : 0;
    $bEven = $b % 2 == 0 ? 1 : 0;
    return $aEven === $bEven ? $a <=> $b : $aEven <=> $bEven;
}); // [1 => 4, 3 => 2, 0 => 5, 2 => 3, 4 => 1]

usort Sort an array by values using a user-defined comparison function

use Barogue\Collections\Collection;

$collection = new Collection([5, 4, 3, 2, 1]);
$collection->sortCallback(function($a, $b) {
    $aEven = $a % 2 == 0 ? 1 : 0;
    $bEven = $b % 2 == 0 ? 1 : 0;
    return $aEven === $bEven ? $a <=> $b : $aEven <=> $bEven;
})->values(); // [1, 3, 5, 2, 4]