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

Get backed enum names as an array of strings in PHP

You can get all case names of a PHP backed enum as an array of strings in the following way:

  1. Call the static cases() method on the backed enum to get an array of all defined cases (in the order of declaration);
  2. Use array_column() on the resulting array of enums, and specify the name (public) property as the column key.

For example:

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

$enumsArr = MyEnum::cases();
$names = array_column($enumsArr, 'name');

var_dump($names); // ['Foo', 'Bar', 'Baz']

It works the same way for pure enums as well.

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