PHP code example of camillebaronnet / collection

1. Go to this page and download the library: Download camillebaronnet/collection library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

camillebaronnet / collection example snippets


public Collection::__construct(...$elements)
public Collection::__construct(\Traversable|array $elements)

$collection = (new Collection('foo', 'bar'))
    ->map(fn($word) => 'hello '.$word)
    ->map(fn($word) => strtoupper($word))
;

// The data is computed only here
var_dump($collection->toArray()); 

map(fn($element) => /* ... */);

(new Collection(10, 50, 100))
    ->map(fn($element) => $element * 2)
    ->toArray()
;

// [20, 100, 200]

filter(fn ($element) => /* ... */);

(new Collection(10, 50, 100))
    ->filter(fn($element) => $element > 20)
    ->toArray()
;
// [50, 100]

reduce(fn($carry, $currentValue, $currentKey) => /* ... */, $initial);


(new Collection(10, 50, 100))
    ->reduce(fn($carry, $current) => $carry + $current)
;
// 160

groupBy(fn ($element) => /* ...  */);

$result = (new Collection([
        ['key1' => 'foo', 'key2' => 10],
        ['key1' => 'bar', 'key2' => 11],
        ['key1' => 'foo', 'key2' => 12],
        ['key1' => 'bar', 'key2' => 14],
    ]))
    ->groupBy(fn($x) => $x['key1'])
    ->toArray() // [CollectionGroup, CollectionGroup]
;

$result[0]->key; // 'foo'
$result[0]->toArray(); // [['key1' => 'foo', 'key2' => 10],['key1' => 'foo', 'key2' => 12],]