1. Go to this page and download the library: Download noctud/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/ */
$list[0]; // throws if missing, get()
$list[0] ?? null; // null if missing
$list->getOrNull(0); // null if missing
$list->firstOrNull(); // null if empty
$map['key']; // throws if missing, get()
$map['key'] ?? null; // null if missing
$map->getOrNull('key'); // null if missing
$map->values->first(); // throws if empty
$set->filter(fn($el) => strlen($el->property) > 3); // new Set<E>
$map->filter(fn($v, $k) => strlen($k->property) > 3); // new Map<K,V>
$map->filterValuesNotNull(); // new Map<K,V> where V is not null
$map->values->filter(fn($v) => $v > 10); // new Collection<V>
$map = mutableMapOf(['a' => 'b']);
if ($map->tracked()->remove('a')->changed) {
// do something only if 'a' was actually removed
}
// Mutable — strict, PHPStan warns on type mismatch
$map = mutableMapOf(['a' => 1]); // MutableMap<string, int>
$map->put('b', 'wrong'); // ❌ PHPStan error: string is not int
// Immutable — widening allowed, returns new instance
$map = mapOf(['a' => 1]); // ImmutableMap<string, int>
$new = $map->put('b', 'text'); // ✅ ImmutableMap<string, int|string>
$map = mutableMapOf(['1' => 'a']); // ❌ Key '1' will be cast to int(1) before the map is created
$map = mutableMapOfPairs([['1', 'a']]); // ✅ Key '1' will stay as a string
$map['2'] = 'b'; // ✅ Key '2' will stay as string
// Enforce string keys (int are only allowed at construction time)
$map = stringMapOf(['1' => 'a', 2 => 'b']); // ✅ Keys '1' and '2' will be strings
// Constructing from a generator
$map = mapOf((function() {
yield '1' => 'a'; // ✅ Key '1' will stay as a string
})());
// The query runs only if $users is actually read
$template->users = listOf(fn() => $repository->getAllUsers());
$lazyMap = mapOf(fn () => ['a' => 1]); // ✅ Good, callback returning an array
$lazyMap = mapOf(fn () => $generator); // ✅ Good, callback returning Generator
$lazyMap->values; // still lazy, no code executed yet
$lazyMap->count(); // first read - executes the callback, materializes the map
$map = mapOfPairs([[$user, 'data']]);
isset($map[$user]); // ✅ True, same object instance
isset($map[clone $user]); // ❌ False, different instance
class User implements \Noctud\Collection\Hashable {
public function identity(): string|int {
return "user_$this->id";
}
}
$map = mutableMapOf();
$map[$user] = 'cacheData';
isset($map[clone $user]); // ✅ True, same user ID