PHP code example of oceanmoon / collections

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

    

oceanmoon / collections example snippets


// Restrict types at runtime
$numbers = new Sequence('int');
$numbers->append(1, 2, 3);    // ✅ Works
$numbers->append('four');      // ❌ InvalidArgumentException

// Union types
$mixed = new Sequence('int|string');
$mixed->append(1, 'two', 3);   // ✅ All work

// Type inference
$seq = new Sequence(source: [1, 2, 3]);
// Automatically infers type as 'int'

// PHP arrays: keys must be string|int
$array = [];
$array[new DateTime()] = 'event';  // ❌ Fatal error
$array[[1, 2]] = 'coords';         // ❌ Illegal offset

// Dictionary: any type works
$dict = new Dictionary();
$dict[new DateTime()] = 'event';         // ✅ Works
$dict[[1, 2, 3]] = 'coordinates';        // ✅ Works
$dict[fopen('file.txt', 'r')] = 'data';  // ✅ Works
$dict[true] = 'yes';                     // ✅ Works
$dict[null] = 'empty';                   // ✅ Works

$numbers = new Sequence('int', source: [1, 2, 3, 4, 5]);

// Method chaining
$result = $numbers
    ->filter(fn($n) => $n % 2 === 0)  // Keep evens
    ->map(fn($n) => $n * 2)            // Double them
    ->reverse();                       // Reverse order

echo $result; // [10, 8, 4]

// Original unchanged (immutable operations)
echo $numbers; // [1, 2, 3, 4, 5]

$set1 = new Set('int', [1, 2, 3, 4]);
$set2 = new Set('int', [3, 4, 5, 6]);

$union = $set1->union($set2);           // {1, 2, 3, 4, 5, 6}
$intersection = $set1->intersect($set2); // {3, 4}
$difference = $set1->diff($set2);        // {1, 2}

// Subset checking
$set1->subset($set2);      // false
$set1->disjoint($set2);  // false

use OceanMoon\Collections\Sequence;

// Create with type inference
$seq = new Sequence(source: [1, 2, 3, 4, 5]);

// Add items
$seq->append(6, 7, 8);
$seq->prepend(0);

// Remove items
$item = $seq->removeByIndex(0);  // Returns removed value
$count = $seq->removeByValue(3); // Returns count removed

// Access items
echo $seq[0];        // 0
echo $seq->first();  // 0
echo $seq->last();   // 8

// Transformations
$evens = $seq->filter(fn($n) => $n % 2 === 0);
$doubled = $seq->map(fn($n) => $n * 2);
$sorted = $seq->sort();

// Aggregations
echo $seq->sum();      // 36
echo $seq->product();  // 0
echo $seq->average();  // 4.5
echo $seq->min();      // 0
echo $seq->max();      // 8

use OceanMoon\Collections\Dictionary;

// Create with type inference
$dict = new Dictionary(source: ['a' => 1, 'b' => 2]);

// Use objects as keys
$dict[new DateTime('2024-01-01')] = 'New Year';

// Use arrays as keys
$dict[[10, 20]] = 'coordinates';

// Type constraints
$typed = new Dictionary('string', 'int');
$typed['count'] = 42;      // ✅ Works
$typed['count'] = 'text';  // ❌ InvalidArgumentException

// Check and access
if ($dict->keyExists('a')) {
    echo $dict['a'];  // 1
}

// Iteration
foreach ($dict as $key => $value) {
    echo "$key => $value\n";
}

use OceanMoon\Collections\Set;

// Duplicates automatically removed
$set = new Set(source: [1, 2, 2, 3, 3, 3]);
echo $set->count(); // 3

// Set operations
$a = new Set('int', [1, 2, 3]);
$b = new Set('int', [2, 3, 4]);

$a->union($b);       // {1, 2, 3, 4}
$a->intersect($b);   // {2, 3}
$a->diff($b);        // {1}

// Membership testing
var_dump($set->contains(2));  // true
var_dump($set->contains(5));  // false