PHP code example of imunhatep / collection

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

    

imunhatep / collection example snippets



    // Read Operations
    $seq = new Sequence([0, 2, 3, 2]);
    $seq->get(2); // int(3)
    $seq->all(); // [0, 2, 3, 2]

    $seq->head(); // Some(0)
    $seq->tail(); // Some(2)

    // Write Operations
    $seq = new Sequence([1, 5]);
    $seq->get(0); // int(1)
    
    $seq
      ->update(0, 4);
      ->get(0); // int(4)
    
    $seq
      ->remove(0)
      ->get(0); // int(5)

    $seq = new Sequence([1, 4]);
    $seq
      ->add(2)
      ->all(); // [1, 4, 2]
    
    $seq
      ->addAll([4, 5, 2])
      ->all(); // [1, 4, 2, 4, 5, 2]

    // Sort
    $seq = new Sequence([0, 5, 4, 2]);
    $seq
      ->sortWith(fn($a, $b) => ($a - $b));
      ->all(); // [0, 2, 4, 5]


    // Read Operations
    $map = new Map(['foo' => 'bar', 'baz' => 'boo']);
    $map->get('foo'); // Some('bar')
    $map->get('foo')->get(); // string('bar')
    $map->keys(); // ['foo', 'baz']
    $map->values(); // ['bar', 'boo']

    $map->headOption(); // Some(['key', 'value'])
    $map->head();       // null | ['key', 'value']
    $map->lastOption(); // Some(['key', 'value'])
    $map->last();       // null | ['key', 'value']
    
    $map->headOption()->getOrElse([]); // ['foo', 'bar']
    $map->lastOption()->getOrElse([]); // ['baz', 'boo']
    
    $map->tail();            // ['baz' => 'boo']

    iterator_to_array($map); // ['foo' => 'bar', 'baz' => 'boo']
    $map->all()              // ['foo' => 'bar', 'baz' => 'boo']

    // Write Operations
    $map = new Map();
    $map->set('foo', 'bar');
    $map->setAll(['bar' => 'baz', 'baz' => 'boo']);
    $map->remove('foo');

    // Sort
    $map->sortWith('strcmp');

    // Transformation
    $map->map(fn($k,$v) => ($value * 2));
    
    $map->flatMap(fn($k,$v) => (new Map())->set($k, $v * 2) );
    
    $map->foldLeft(SomeObject $s, fn($s, $k, $v) => $s->add([$k, $v * 2]))

    class DateTimeHashable extends \DateTime implements HashableInterface
    {
        public function hash(): string
        {
            return $this->format("YmdP");
        }
    }
    
    $set = new Set();
    $set->add(new DateTimeHashable('today'));
    $set->add(new DateTimeHashable('today'));

    var_dump(count($set)); // int(1) -> the same date is not added twice

    foreach ($set as $date) {
        var_dump($date);
    }

    $set->all();
    $set->addSet($otherSet);
    $set->addAll($someElements);

    // Traverse
    $set->map(function($x) { return $x*2; });
    $set->flatMap(function($x) { return [$x*2, $x*4]; });