#development #pattern #php

When you use enums in PHP, there is no easy way to get the values or names as an array.

This is something which cane easily be fixed with a simple trait like this:

trait HasEnumToArray
{
    public static function names(): array
    {
        return array_column(self::cases(), 'name');
    }

    public static function values(): array
    {
        return array_column(self::cases(), 'value');
    }

    public static function array(): array
    {
        return array_combine(self::values(), self::names());
    }
}

To use it, add the use HasEnumToArray directive into your enum and you're all set.

enum SampleEnum: string
{
    use HasEnumToArray;

    case NameA = 'value_a';
    case NameB = 'value_b';
    case NameC = 'value_c';
}

// Getting the values
SampleEnum::values();
// ['value_a', 'value_b', 'value_c']

// Getting the names
SampleEnum::names();
// ['NameA', 'NameB', 'NameC']

// Getting them as an array
SampleEnum::array();
// [
//     'value_a' => 'NameA',
//     'value_b' => 'NameB',
//     'value_c' => 'NameC',
// ]