PHP : How to set an array of enum values with type check and deduplication ?

| 1 min read

Enum is a very powerful addition to PHP in replacement of constants to be able to set defined values as an argument of a method, in a property, etc.

And with type check, you ensure the value given is one of the enum.

But what if we need to set multiple enum values to our method or property, as an array ? PHPDoc is available to indicate what type we expect in the array, but we won't have any type check.

So how to do that ? Variadic arguments to the rescue :

<?php

enum Fruit: string {
    case Apple = 'apple';
    case Banana = 'banana';
    case Cherry = 'cherry';
}

class FruitBasket
{
    protected array $fruits = [];

    public function __construct(array $fruits)
    {
        $this->setVariadicFruits(...$fruits);
    }

    protected function setVariadicFruits(Fruit ...$fruits): void
    {
        $this->fruits = array_unique($fruits, SORT_REGULAR);
    }
}

$basket = new FruitBasket([Fruit::Apple, Fruit::Banana, Fruit::Cherry, Fruit::Banana, Fruit::Cherry]);