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


use OmegaAlfa\Collection\Collection;
use OmegaAlfa\Collection\LazyFileIterator;

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

// Iterate over the collection
foreach ($collection as $item) {
    echo $item . PHP_EOL;
}

// Map the collection
$collection->addIterator(new ArrayIterator([6, 7, 8]));
$squaredNumbers = $collection->map(function ($item) {
    return $item * $item;
});

// Filter the collection
$evenNumbers = $collection->filter(function ($item) {
    return $item % 2 === 0;
});

// Apply a callback to each item in the collection
$collection->each(function ($item) {
    echo "Item: $item" . PHP_EOL;
});

// Get the number of items in the collection
$count = $collection->count();

// Add an item to the collection
$collection->add(6);

// Remove an item from the collection
$collection->remove(3);

// Convert the collection to an array
$array = $collection->toArray();

// Search for a value in a multidimensional array
$value = $collection->searchValueKey([
    'name' => 'John Doe',
    'address' => [
        'street' => 'Main Street',
        'city' => 'Anytown',
    ],
], 'city');

echo $value; // Output: Anytown

$iterator = new LazyFileIterator('path/to/your/json_file.json');
$collection = new Collection($iterator);

foreach ($collection as $item) {
    // Process each JSON object from the file
    echo $item->name . PHP_EOL;
}