How to Get an Array of All Backed Enum Cases 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()).


This post was published 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.