PHP code example of omegaalfa / collection

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

    

omegaalfa / collection example snippets


Sequence<User>
Map<string, Config>

LazySequence::range(1, 1M)
  ->take(10) // Only 10 iterations!

$new = $seq->append(42);
// Original unchanged

use Omegaalfa\Collection\Collection;

// Create from array or Iterator
$collection = new Collection([1, 2, 3, 4, 5]);

// Transform (eager)
$doubled = $collection->map(fn($x) => $x * 2);
$evens = $collection->filter(fn($x) => $x % 2 === 0);

// 🚀 Lazy methods (memory efficient!)
$result = Collection::lazyRange(1, 1000000)
    ->lazyMap(fn($x) => $x * 2)
    ->lazyFilter(fn($x) => $x > 100)
    ->lazyTake(10);  // Only processes ~51 elements!

// Array access
$collection['key'] = 'value';
echo $collection['key'];

// Statistics
echo $collection->sum();    // 15
echo $collection->avg();    // 3
echo $collection->count();  // 5

use Omegaalfa\Collection\Sequence;

// Create
$numbers = Sequence::of(1, 2, 3, 4, 5);
$range = Sequence::range(1, 10);

// Immutable transformations
$doubled = $numbers->map(fn($x) => $x * 2);
$evens = $numbers->filter(fn($x) => $x % 2 === 0);

// 🔗 Fluent chaining
$result = Sequence::range(1, 100)
    ->filter(fn($x) => $x % 3 === 0)
    ->map(fn($x) => $x * $x)
    ->take(5);

// Access
echo $numbers->at(0);      // 1
echo $numbers->first();    // 1
echo $numbers->last();     // 5

// Operations (returns new Sequence)
$appended = $numbers->append(6);
$prepended = $numbers->prepend(0);
$inserted = $numbers->insert(2, 99);
$removed = $numbers->remove(2);

use Omegaalfa\Collection\Map;

// Create
$user = Map::of(
    'name', 'John',
    'age', 30,
    'city', 'NY'
);

// Access
echo $user->get('name');               // John
echo $user->getOrDefault('email', '-'); // -

// Transform (returns new Map)
$aged = $user->put('age', 31);
$removed = $user->remove('city');

// 🔄 Transformations
$uppercased = $user->mapValues(fn($k, $v) => is_string($v) ? strtoupper($v) : $v);
$prefixed = $user->mapKeys(fn($k) => "user_$k");

// Merge
$merged = $user->merge(Map::of('email', '[email protected]'));

use Omegaalfa\Collection\LazySequence;

// 🚀 Pipeline - NOTHING executes until iteration!
$pipeline = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);

// Now it executes - only ~51 iterations!
foreach ($pipeline as $value) {
    echo $value;  // 102, 104, 106...
}

// ⚡ Short-circuit operations
$first = LazySequence::range(1, 1000000)->first();  // Stops at 1

// Materialize to eager
$eager = $lazy->toEager();  // Returns Sequence

use Omegaalfa\Collection\LazyMap;

// Values are closures - computed on-demand! 💡
$config = LazyMap::from([
    'database' => fn() => new Database(),  // Not created yet
    'cache' => fn() => new Redis(),        // Not created yet
    'api' => fn() => new ApiClient()       // Not created yet
]);

// ⚡ Only creates Database when accessed
$db = $config->get('database');

// 🆕 With LazyProxyObject (PHP 8.4+)
$services = LazyMap::ofLazyObjects([
    'logger' => [Logger::class, $config],
    'mailer' => [Mailer::class, $smtp]
]);

// Creates lazy proxy - object instantiated on first method call
$logger = $services->get('logger');
$logger->info('message');  // NOW Logger is instantiated

use Omegaalfa\Collection\LazyFileIterator;

// 📄 Stream JSON lines file (memory efficient!)
$iterator = new LazyFileIterator('data.jsonl');

foreach ($iterator as $index => $object) {
    echo "Line {$index}: {$object->name}\n";
}

// Use with Collection for transformations
$collection = new Collection($iterator);
$filtered = $collection->lazyFilter(fn($obj) => $obj->active);

map(callable $fn): self           // Transform each element
filter(callable $fn): self        // Keep matching elements
flatMap(callable $fn): self       // Map + flatten
reduce(callable $fn, mixed $init) // Reduce to single value

sum(): int|float                  // Sum all numeric values
avg(): int|float                  // Calculate average
min(): mixed                      // Find minimum
max(): mixed                      // Find maximum
count(): int                      // Count elements

first(): mixed                    // Get first element
last(): mixed                     // Get last element
find(callable $fn): mixed         // Find matching element
any(callable $fn): bool           // Check if any matches
all(callable $fn): bool           // Check if all match

take(int $n): self               // Take first n elements
skip(int $n): self               // Skip first n elements
chunk(int $size): self           // Split into chunks
takeWhile(callable $fn): self    // Take while predicate true
skipWhile(callable $fn): self    // Skip while predicate true

// Processes 1M elements
$data = range(1, 1000000);
$result = array_map(
    fn($x) => $x * 2,
    array_filter($data, fn($x) => $x % 2 === 0)
);

// Only processes 51 elements!
$result = LazySequence::range(1, 1000000)
    ->map(fn($x) => $x * 2)
    ->filter(fn($x) => $x > 100)
    ->take(10);
bash
php benchmark.php