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

You can get an array of all values of a backed enum in PHP, 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 value (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();
$values = array_column($enumsArr, 'value');

var_dump($values); // ['foo', 'bar', 'baz']

You can also add a custom method to the enum that returns all case values as an array, for example, like so:

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

    public static function getAllValues(): array
    {
        return array_column(MyEnum::cases(), 'value');
    }
}

var_dump(MyEnum::getAllValues()); // ['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.