PHP code example of binary-cats / shard-collections

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

    

binary-cats / shard-collections example snippets


use Illuminate\Support\Collection;

$collection = collect([1, 2, 3]);

$map = [
    fn ($item) => $item > 10,  // First condition
    fn ($item) => $item < 2,   // Second condition
];

$output = $collection->shard($map);

// Result:
// [
//     collect([]),           // Items > 10 (none)
//     collect([1]),          // Items < 2
//     collect([2, 3])        // Remaining items
// ]

$output = $collection->shard($map, true);

// Result:
// [
//     collect([]),           // Items > 10 (none)
//     collect([0 => 1]),     // Items < 2 (with original keys)
//     collect([1 => 2, 2 => 3]) // Remaining items (with original keys)
// ]


$output = $collection->shard(
    map: $map, 
    forceRemainder: true
);

// Result:
// [
//     collect(['one' => 1, 'two' => 2, 'three' => 3]), // Remaining items
//     collect([]) // Remainder is empty, but is 

$collection = collect([1, 2, 3]);

$map = [
    'high' => fn ($item) => $item > 10,  // First condition
    'low' => fn ($item) => $item < 2,    // Second condition
];

$output = $collection->shardWithKeys($map, 'medium');

// Result:
// [
//     'high' => collect([]),    // Items > 10 (none)
//     'low' => collect([1]),     // Items < 2
//     'medium' => collect([2, 3]) // Remaining items
// ]

$output = $collection->shardWithKeys($map, 'medium', true);

// Result:
// [
//     'high' => collect([]),           // Items > 10 (none)
//     'low' => collect([0 => 1]),      // Items < 2 (with original keys)
//     'medium' => collect([1 => 2, 2 => 3]) // Remaining items (with original keys)
// ]

$collection = collect(['one' => 1, 'two' => 2, 'three' => 3]);

$map = [
    'small' => fn ($item) => $item < 2,
    'large' => fn ($item) => $item > 10,
];

$output = $collection->shardWithKeys($map, 'medium', true);

// Result:
// [
//     'small' => collect(['one' => 1]),
//     'large' => collect([]),
//     'medium' => collect(['two' => 2, 'three' => 3])
// ]

collect(['one' => 1, 'two' => 2, 'three' => 3])->shard(
    map: [fn ($item) => $item < 10],
    forceRemainder: true
);

// Result:
// [
//     collect(['one' => 1, 'two' => 2, 'three' => 3]) // Remaining items
//     collect([]) // Remainder is empty, but is 

$collection = collect([1, 2, 3]);

$output = $collection->shard([]);
// Result: [collect([1, 2, 3])]

$output = $collection->shardWithKeys([], 'all');
// Result: ['all' => collect([1, 2, 3])]