PHP code example of tiny-blocks / collection

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

    

tiny-blocks / collection example snippets




declare(strict_types=1);

namespace Example;

use TinyBlocks\Collection\Collection;
use TinyBlocks\Collection\Internal\Operations\Order\Order;
use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys;

$collection = Collection::createFrom(elements: [1, 2, 3, 4, 5])
    ->add(elements: [6, 7]) 
    ->filter(predicates: fn(int $value): bool => $value > 3) 
    ->sort(order: Order::ASCENDING_VALUE) 
    ->map(transformations: fn(int $value): int => $value * 2) 
    ->toArray(preserveKeys: PreserveKeys::DISCARD); 

# Output: [8, 10, 12, 14]

  $collection->add(elements: [1, 2, 3]);
  

  $collection ->add('X', 'Y', 'Z');
  

  $collection->remove(element: 1);
  

      $collection->removeAll(filter: fn(Amount $amount): bool => $amount->value > 10.0);
      

      $collection->removeAll();
      

      $collection->filter(predicates: fn(Amount $amount): bool => $amount->value > 100);
      

      $collection->filter();
      

  use TinyBlocks\Collection\Internal\Operations\Order\Order;
        
  $collection->sort(order: Order::DESCENDING_VALUE);
  

  use TinyBlocks\Collection\Internal\Operations\Order\Order;
        
  $collection->sort(order: Order::ASCENDING_VALUE, predicate: fn(Amount $amount): float => $amount->value);
  

  $collection->count();
  

  $collection->findBy(predicates: fn(CryptoCurrency $crypto): bool => $crypto->symbol === 'ETH');
  

  $collection->first(defaultValueIfNotFound: 'default');
  

  $collection->getBy(index: 0, defaultValueIfNotFound: 'default');
  

  $collection->last(defaultValueIfNotFound: 'default');
  

  $collection->slice(index: 1, length: 2);
  

  $collection->contains(element: 5);
  

  $collectionA->equals(other: $collectionB);
  

  $collection->reduce(aggregator: fn(float $carry, float $amount): float => $carry + $amount, initial: 0.0)
  

  $collection->each(actions: fn(Invoice $invoice): void => $collectionB->add(elements: new InvoiceSummary(amount: $invoice->amount, customer: $invoice->customer)));
  

  $collection->groupBy(grouping: fn(Amount $amount): string => $amount->currency->name);
  

  $collection->map(transformations: fn(int $value): int => $value * 2);
  

  use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys;
  
  $collection->toArray(preserveKeys: PreserveKeys::DISCARD);
  

  use TinyBlocks\Collection\Internal\Operations\Transform\PreserveKeys;
  
  $collection->toJson(preserveKeys: PreserveKeys::DISCARD);