
Getting the names and values of an enum using a trait
10 Aug 2022 #pattern #development #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 valuesSampleEnum::values();// ['value_a', 'value_b', 'value_c'] // Getting the namesSampleEnum::names();// ['NameA', 'NameB', 'NameC'] // Getting them as an arraySampleEnum::array();// [// 'value_a' => 'NameA',// 'value_b' => 'NameB',// 'value_c' => 'NameC',// ]