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()).


This post was published (and was last revised ) by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.