PHP code example of palmtree / collection

1. Go to this page and download the library: Download palmtree/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/ */

    

palmtree / collection example snippets


use function Palmtree\Collection\c;

$collection = c(['foo' => 'bar', 'baz' => 'qux']);

$foo = $collection['foo'];
$collection['baz2'] = 'qux';

isset($collection['baz']); // true
unset($collection['baz']);
count($collection);

foreach ($collection as $key => $value) {
    // do stuff with value and/or key
}

// find returns the first matching element
$foo = $collection->find(fn ($v) => $v === 'bar');

// filter returns a new filtered collection
$quxCollection = $collection->filter(fn ($v) => $v === 'qux');

use function Palmtree\Collection\c;

$collection = c([1, 9, 5, 3, 7, 10])
    ->sort()
    ->filter(fn ($i) $i < 10)
    ->values()

// returns true as every element remaining in the collection is odd
$isAllOdd = $collection->every(fn ($i) => $i % 2 !== 0);
// returns false as it was removed in our filter
$collection->contains(10);

// returns true as at least one of the elements is false
c([true, true, false, true, true])->some(fn ($v) => !$v);

/** @var Collection<int, Foo> **/
$collection = new Collection();
$collection->add(new Foo());

foreach ($collection as $foo) {
    // Psalm/PHPStan and PhpStorm know that $foo is an instance of Foo here
}