#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:

 1trait HasEnumToArray
 2{
 3    public static function names(): array
 4    {
 5        return array_column(self::cases(), 'name');
 6    }
 7
 8    public static function values(): array
 9    {
10        return array_column(self::cases(), 'value');
11    }
12
13    public static function array(): array
14    {
15        return array_combine(self::values(), self::names());
16    }
17}

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

 1enum SampleEnum: string
 2{
 3    use HasEnumToArray;
 4
 5    case NameA = 'value_a';
 6    case NameB = 'value_b';
 7    case NameC = 'value_c';
 8}
 9
10// Getting the values
11SampleEnum::values();
12// ['value_a', 'value_b', 'value_c']
13
14// Getting the names
15SampleEnum::names();
16// ['NameA', 'NameB', 'NameC']
17
18// Getting them as an array
19SampleEnum::array();
20// [
21//     'value_a' => 'NameA',
22//     'value_b' => 'NameB',
23//     'value_c' => 'NameC',
24// ]