PHP code example of blueprintau / collections
1. Go to this page and download the library: Download blueprintau/collections 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/ */
blueprintau / collections example snippets
use BlueprintAU\Collections\Collection;
// Constructors are protected — create instances via the static factories.
$users = Collection::make([
['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
['id' => 2, 'name' => 'Bob', 'role' => 'user'],
['id' => 3, 'name' => 'Carol', 'role' => 'user'],
]);
// Transforms (immutable — each returns a new Collection)
$names = $users->pluck('name'); // ['Alice', 'Bob', 'Carol']
$byId = $users->keyBy('id'); // [1 => [...], 2 => [...], 3 => [...]]
$byRole = $users->groupBy('role'); // ['admin' => [...], 'user' => [...]]
$admins = $users->filter(fn ($u) => $u['role'] === 'admin'); // [Alice]
$upper = $users->map(fn ($u) => strtoupper($u['name'])); // ['ALICE', 'BOB', 'CAROL']
// Predicate & streaming transforms
$young = $users->filterMap(fn ($u) => $u['age'] < 18 ? $u['name'] : null); // nulls dropped, keys preserved
$notAdmin = $users->reject(fn ($u) => $u['role'] === 'admin');
$prefix = Collection::make([1, 2, 3, 9])->takeWhile(fn ($v) => $v < 3); // [1, 2]
$from3 = Collection::make([1, 2, 3, 9])->skipUntil(fn ($v) => $v === 3); // [3, 9]
// Reductions
$count = $users->count(); // 3
$total = Collection::make([1, 2, 3, ̀4])->sum(); // 10
$avg = Collection::make([1, 2, 3, 4])->avg(); // 2.5
$hasAdmin = $users->contains(fn ($u) => $u['role'] === 'admin'); // true
$empty = $users->isNotEmpty(); // true
$only = $users->sole('id', 1); // Alice's row (throws on 0 or 2+ matches)
$csv = $users->implode(', ', 'name'); // 'Alice, Bob, Carol'
// Selection
$firstTwo = $users->take(2); // [Alice, Bob]
$sorted = Collection::make([
['name' => 'Carol'],
['name' => 'Alice'],
['name' => 'Bob'],
])->sortBy('name'); // [Alice, Bob, Carol]
$unique = Collection::make([1, 1, 2, ̀3, ̀3])->unique(); // [1, 2, 3]
// Iteration
$users->each(fn ($u) => print($u['name'] . "\n")); // Alice Bob Carol
$first = $users->first(); // Alice's row
$firstUser = $users->firstWhere('role', 'user'); // Bob's row
// Conversion
$array = $users->toArray(); // plain array
$json = $users->toJson(); // JSON string
use BlueprintAU\Collections\LazyCollection;
// An infinite sequence, safely truncated.
$lazy = LazyCollection::make(function (): \Generator {
$i = 1;
while (true) {
yield $i++;
}
});
$firstFive = $lazy->take(5)->all(); // [1, 2, 3, 4, 5]