PHP code example of seboettg / collection

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

    

seboettg / collection example snippets




use function Seboettg\Collection\Lists\listOf;
use function Seboettg\Collection\Lists\listFromArray;
//create a simple list
$list = listOf("a", "b", "c", "d");
print_r($list);

$array = ["d", "e", "f"];
$otherList = listFromArray($array);

use function Seboettg\Collection\Lists\emptyList;
$emptyList = emptyList();
echo $emptyList->count();

foreach ($list as $key => $value) {
    echo "[".$key."] => ".$value."\n";
}

for ($i = 0; $i < $otherList->count(); ++$i) {
    echo $otherList->get($i) . " ";
}

$newList = $list->plus($otherList);
print_r($newList);

$newList = $list->plus($array);

$subtract = $newList->minus($list);
print_r($subtract);

$intersection = $newList->intersect(listOf("b", "d", "f", "h", "i"));
print_r($intersection);

$list = listOf("a", "b", "a", "d", "e", "e", "g")
print_r($list->distinct());

$list = listOf(1, 2, 3, 4, 5);
$cubicList = $list->map(fn ($i) => $i * $i * $i);
//result of $cubicList: 1, 8, 27, 64, 125

function divisibleByTwoOrNull(int $number): ?int {
    return $item % 2 === 0 ? $item : null;
}

listOf(0, 1, 2, 3, 4, 5)
    ->map(fn (int $number): ?int => divisibleByTwoOrNull($number));
//result: 0, 2, 4


$list = listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"):
$listOfCharactersThatAsciiNumbersIsOdd = $list
    ->filter(fn($letter) => ord($letter) % 2 !== 0);
//result of $listOfCharactersTharOrderNumbersAreOdd: "a", "c", "e", "g", "i"

$list = listOf("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"):
$list->all(fn($letter) => ord($letter) % 2 !== 0); // false
$list->any(fn($letter) => ord($letter) % 2 !== 0); // true

$list->all(fn($letter) => ord($letter) % 1 !== 0); // true
$list->any(fn($letter) => $letter === "z"); // false, since no character in the list is a 'z'

$list = listOf("a", "b", "c");
$list->forEach(fn (string $item) => print($item . PHP_EOL));


namespace Vendor\App\Model;
use Seboettg\Collection\Comparable\Comparable;
class Element implements Comparable
{
    private $attribute1;
    private $attribute2;
    
    //contructor
    public function __construct($attribute1, $attribute2)
    {
        $this->attribute1 = $attribute1;
        $this->attribute2 = $attribute2;
    }
    
    // getter
    public function getAttribute1() { return $this->attribute1; }
    public function getAttribute2() { return $this->attribute2; }
    
    //compareTo function
    public function compareTo(Comparable $b): int
    {
        return strcmp($this->attribute1, $b->getAttribute1());
    }
}


namespace Vendor\App\Util;

use Seboettg\Collection\Comparable\Comparator;
use Seboettg\Collection\Comparable\Comparable;

class Attribute1Comparator extends Comparator
{
    public function compare(Comparable $a, Comparable $b): int
    {
        if ($this->sortingOrder === Comparator::ORDER_ASC) {
            return $a->compareTo($b);
        }
        return $b->compareTo($a);
    }
}


use Seboettg\Collection\Lists;
use Seboettg\Collection\Collections;
use Seboettg\Collection\Comparable\Comparator;
use function Seboettg\Collection\Lists\listOf;
use Vendor\App\Util\Attribute1Comparator;
use Vendor\App\Model\Element;


$list = listOf(
    new Element("b","bar"),
    new Element("a","foo"),
    new Element("c","foobar")
);

Collections::sort($list, new Attribute1Comparator(Comparator::ORDER_ASC));



use Seboettg\Collection\Comparable\Comparator;
use Seboettg\Collection\Comparable\Comparable;
use Seboettg\Collection\Lists;
use Seboettg\Collection\Collections;
use function Seboettg\Collection\Lists\listOf;
use Vendor\App\Model\Element;

//Define a custom Comparator
class MyCustomOrderComparator extends Comparator
{
    public function compare(Comparable $a, Comparable $b): int
    {
        return (array_search($a->getAttribute1(), $this->customOrder) >= array_search($b->getAttribute1(), $this->customOrder)) ? 1 : -1;
    }
}

$list = listOf(
    new Element("a", "aa"),
    new Element("b", "bb"),
    new Element("c", "cc"),
    new Element("k", "kk"),
    new Element("d", "dd"),
);

Collections::sort(
    $list, new MyCustomOrderComparator(Comparator::ORDER_CUSTOM, ["d", "k", "a", "b", "c"])
);


use Seboettg\Collection\Map\Pair;
use function Seboettg\Collection\Map\pair;
use function Seboettg\Collection\Map\mapOf;

$pair1 = pair("Ceres", "Giuseppe Piazzi")

//or you use the factory, with the same result:
$pair2 = Pair::factory("Pallas", "Heinrich Wilhelm Olbers");

//Now you can add both pairs to a map
$map = mapOf($pair1, $pair2);
print_r($map);

use function Seboettg\Collection\Map\emptyMap;
$emptyMap = emptyMap();
echo $emptyMap->count();

use function Seboettg\Collection\Map\mapOf;
$asteroidExplorerMap = mapOf(
    pair("Ceres", "Giuseppe Piazzi"),
    pair("Pallas", "Heinrich Wilhelm Olbers"),
    pair("Juno", "Karl Ludwig Harding"),
    pair("Vesta", "Heinrich Wilhelm Olbers")
);

$juno = $asteroidExplorerMap->get("Juno"); //Karl Ludwig Harding

// or access elements like an array
$pallas = $asteroidExplorerMap["Pallas"]; //Heinrich Wilhelm Olbers

//get a list of all keys
$asteroids = $asteroidExplorerMap->getKeys(); //Ceres, Pallas, Juno, Vesta

//get a list of all values
$explorer = $asteroidExplorerMap
    ->values()
    ->distinct(); // "Giuseppe Piazzi", "Heinrich Wilhelm Olbers", "Karl Ludwig Harding"

$explorer = $asteroidExplorerMap
    ->getOrElse("Iris", fn() => "unknown"); //$explorer = "unknown"


$keyValuePairs = $asteroidExplorerMap->getEntries();

use function Seboettg\Collection\Map\emptyMap;

$map = emptyMap();

//put
$map->put("ABC", 1);
echo $map["ABC"]; // 1

//put via array assignment
$map["ABC"] = 2;
echo $map["ABC"]; // 2

//remove
$map->put("DEF", 3);
$map->remove("DEF");
echo $map->get("DEF"); // null

use function Seboettg\Collection\Map\mapOf;

class Asteroid {
    public string $name;
    public ?string $explorer;
    public ?float $diameter;
    public function __construct(string $name, string $explorer, float $diameter = null)
    {
        $this->name = $name;
        $this->explorer = $explorer;
        $this->diameter = $diameter;
    }
}

$asteroids = $asteroidExplorerMap
    ->map(fn (Pair $pair): Asteroid => new Asteroid($pair->getKey(), $pair->getValue()));

print_r($asteroids);

$asteroids = $asteroidExplorerMap
    ->map(fn (string $key, string $value): Asteroid => new Asteroid($key, $value));

$asteroidExplorerMap->filter(fn (Pair $pair): bool => $pair->getKey() !== "Juno");

$asteroidExplorerMap->filter(fn (string $key, string $value): bool => $key !== "Juno");

use function Seboettg\Collection\Lists\listFromArray;

class Customer {
    public string $id;
    public string $lastname;
    public string $firstname;
    public DateTime $createDate;
    public function __construct(
        string $id,
        string $lastname,
        string $firstname,
        DateTime $createDate
    ) {
        $this->id = $id;
        $this->lastname = $lastname;
        $this->firstname = $firstname;
        $this->createDate = $createDate;
    }
}

$customerList = listFromArray(json_decode(file_get_contents("customer.json"), true));
$customerMap = $customerList
    ->filter(fn (array $customerArray) => $customerArray["lastname"] === "Doe") // filter for lastname Doe
    ->map(fn (array $customerArray) => new Customer(
        $customerArray["id"],
        $customerArray["lastname"],
        $customerArray["firstname"],
        DateTime::createFromFormat("Y-m-d H:i:s", $customerArray["createDate"])
     )) // map array to customer object
    ->associateBy(fn(Customer $customer) => $customer->id); // link the id with the respective customer object
print_($customerMap);

$listOfIds = listOf("A001", "A002", "A004");
$customerMap = $listOfIds
    ->associateWith(fn ($customerId) => $customerService->getById($customerId))

$stack = new Stack();
$stack->push("a")
      ->push("b")
      ->push("c");
echo $stack->pop(); // outputs c
echo $stack->count(); // outputs 2

// peek returns the element at the top of this stack without removing it from the stack.
echo $stack->peek(); // outputs b
echo $stack->count(); // outputs 2

echo $stack->search("c"); //outputs 0 since c does not exist anymore
echo $stack->search("a"); //outputs 2
echo $stack->search("b"); //outputs 1

$queue = new Queue();
$queue->enqueue("d")
    ->enqueue("z")
    ->enqueue("b")
    ->enqueue("a");
    
echo $queue->dequeue(); // outputs d
echo $queue->dequeue(); // outputs z
echo $queue->dequeue(); // outputs b
echo $queue->count(); // outputs 1
bash
# Install Composer
curl -sS https://getcomposer.org/installer | php
bash
php composer.phar 

Seboettg\Collection\Map\MapInterface@anonymous Object
(
    [array:Seboettg\Collection\Map\MapInterface@anonymous:private] => Array
        (
            [A001] => Customer Object
                (
                    [id] => A001
                    [lastname] => Doe
                    [firstname] => John
                    [createDate] => DateTime Object
                        (
                            [date] => 2022-06-10 09:21:12.000000
                            [timezone_type] => 3
                            [timezone] => UTC
                        )

                )
            [A002] => Customer Object
                (
                    [id] => A002
                    [lastname] => Doe
                    [firstname] => Jane
                    [createDate] => DateTime Object
                        (
                            [date] => 2022-06-10 09:21:13.000000
                            [timezone_type] => 3
                            [timezone] => UTC
                        )
                )
        )
)