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

Get backed enum cases as a list in PHP

You can get all cases defined in a PHP backed enum as an array by calling the static cases() method on the enum:

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

The return value of the static cases() method is an array of all defined enum cases in the order of their declaration. For example:

// PHP 8.1+
enum MyEnum: string
{
    case Foo = 'foo';
    case Bar = 'bar';
    case Baz = 'baz';
}

$cases = MyEnum::cases();

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

echo $cases[0]->name; // 'Foo'
echo $cases[0]->value; // '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 . Please show your love and support by sharing this post.