PHP code example of hyqo / collection

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

    

hyqo / collection example snippets


class Product 
{
    public $title;
    public $amount;
    
    public function __construct(string $title, int $amount){
        $this->title = $title;
        $this->amount = $amount;
    }
}

use \Hyqo\Collection\Collection;
use function \Hyqo\Collection\collect;

$collection = new Collection([new Product('foo', 10), new Product('bar', 2)]);
$collection = collect([new Product('foo', 10), new Product('bar', 2)]);

use Hyqo\Collection\Collection;

$collection = new Collection([new Product('foo', 10), new Product('bar', 2)]);

use Hyqo\Collection\Collection;

/** @var Collection<Product> $collection */
$collection = new Collection();

use Hyqo\Collection\Collection;

/** @extends Collection<Product> */
class ProductCollection extends Collection 
{
}


$collection = new ProductCollection();

function add($item): static

$collection->add($item);

function get(int $index): T|null

$collection->get(0);

function each(callable $closure): static<T>

$collection->each(function(Product $product) {
    // do something
});

function map(callable $closure): static<T>

$collection->map(function(Product $product) {
    // do something
    return $product;
});

function reduce(callable $closure, $initial = null): mixed|null

$collection = new Collection([new Product('foo', 10), new Product('bar', 2)]);

$amount = $collection->reduce(function($carry, Product $product) {
    return $carry + $product->amount;
});

// 4

function slice(int $first, ?int $length = null): static<T>

$collection->slice(3);

function copy(): static<T>

$collection->copy();

function chunk(int $length): \Generator<static<T>>

$collection->chunk(10);

function filter(callable $closure): static<T>

$collection->filter(function(Product $product){
    return $product->amount > 1;
});

function toArray(?callable $closure = null): array

$collection->toArray(); // [Product, Product]

$collection->toArray(function(Product $product) {
    return $product->title;
}); // ['foo', 'bar']

$collection->toArray(function(Product $product): \Generator {
    yield $product->title => $product->amount;
}); // ['foo'=>10, 'bar'=>2]