How to Get an Array of All Enum Cases in PHP?

To get all cases of a PHP enum, you can simply call the static cases() method on it:

// PHP 8.1+
MyEnum::cases();

This would return an array of all defined enum cases in the order of declaration. For example:

// PHP 8.1+
enum MyEnum
{
    case Foo;
    case Bar;
    case Baz;
}

$cases = MyEnum::cases();

var_dump($cases); // [enum(MyEnum::Foo), enum(MyEnum::Bar), enum(MyEnum::Baz)]

echo $cases[0]->name; // 'Foo'

The static cases() method is available on both, pure enums and backed enums, as they both implement the common, internal interface named UnitEnum (which includes the static method cases()).


Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.