bluzphp/collection

Collection package

2.2.0 2024-09-10 11:37 UTC

This package is auto-updated.

Last update: 2024-10-10 11:52:07 UTC


README

Achievements

PHP >= 8.2+

Latest Stable Version

Build Status

Scrutinizer Code Quality

Total Downloads

License

Usage

Example of an array:

$arr = [
    'a', 
    'b' => 'boo',
    'c' => [
        'c1',
        'c2',
        'c3'
    ],
    'd' => [
        'd1' => ['d1.1', 'd1.2'],
        'd2' => ['d2.1', 'd2.2'],
        'd3' => ['d3.1', 'd3.2'],
    ],
    'e' => null,
    'f' => false
];

Check the element by key(s)

Usage:

Collection::has(array $array, ...$keys);
array_has($array, ...$keys);

Examples:

array_has($array, 0);         // true 
array_has($array, 'b');       // true
array_has($array, 'c', 0);    // true
array_has($array, 'd', 'd1'); // true
array_has($array, 'e');       // true
array_has($array, 'f');       // true
array_has($array, 'g');       // false

Compare to isset():

isset($array['e']); // false

Get the element by key(s)

Usage:

Collection::get(array $array, ...$keys);
array_get(array $array, ...$keys);

Examples:

array_get($array, 0);         // 'a' 
array_get($array, 'b');       // 'boo'
array_get($array, 'c', 0);    // 'c1'
array_get($array, 'd', 'd1'); // ['d1.1', 'd1.2']
array_get($array, 'e');       // null
array_get($array, 'e', 'e');  // null

Add the element to the array by key(s)

Usage:

Collection::add(array &$array, $key, ...$values);
array_add(array &$array, $key, ...$values);

Examples:

array_add($array, 'c', 'c3');           // $array['c'][] = 'c3'
array_add($array, 'd', 'd1', 'd1.3');   // $array['d']['d1'][] = 'd1.3'
array_add($array, 'g', 'g1', 'g1.1');   // $array['g']['g1'][] = 'g1.1'

// but
array_add($array, 'b', 'b1');           // InvalidArgumentException - $array['b'] is not an array

Set the element of the array by key(s)

This method is similar to native way.

Usage:

Collection::set(array &$array, $key, ...$values);
array_set(array &$array, $key, ...$values);

Examples:

array_set($array, 'g', 'game over');       // $array['g'] = 'game over';
array_set($array, 'h', 'high way', 'e95'); // $array['h']['high way'] = 'e95';