You can get all case
names of a PHP enum as an array of strings in the following way:
- Call the static
cases()
method on the enum to get an array of all defined cases (in the order of declaration); - Use
array_column()
on the resulting array of enums, and specify thename
(public) property as the column key.
For example:
// PHP 8.1+
enum MyEnum
{
case Foo;
case Bar;
case Baz;
}
$enumsArr = MyEnum::cases();
$names = array_column($enumsArr, 'name');
var_dump($names); // ['Foo', 'Bar', 'Baz']
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.