'Getting values for an enum?

I have an enum:

enum Type: int
{
    case OFFENSIVE = 1;
    case SPAM = 2;
    case IRRELEVANT = 3;
}

I understand I can get all types and their values with Type::cases(), but how can I just get the values (1,2,3) for an enum?



Solution 1:[1]

cases() returns the individual enum objects; getting their associated values is a case of looking at ->value on each one. In full:

$values = [];
foreach ( Type::cases() as $case ) {
    $values[] = $case->value;
}

Fortunately, there is a built-in function array_column which basically performs this loop for you:

$values = array_column(Type::cases(), 'value');

You can also specify what you want to be the key of the resulting array, so lots of variations are possible depending what you need:

$enum_objects_as_list = Type::cases();
// [Type::OFFENSIVE, Type::SPAM, Type::IRRELEVANT]

$values_as_list = array_column(Type::cases(), 'value');
// [1, 2, 3]

$names_as_list = array_column(Type::cases(), 'name');
// ['OFFENSIVE', 'SPAM', 'IRRELEVANT']

$name_to_value_lookup = array_column(Type::cases(), 'value', 'name');
// ['OFFENSIVE' => 1, 'SPAM' => 2, 'IRRELEVANT' => 3]

$value_to_name_lookup = array_column(Type::cases(), 'name', 'value');
// [1 => 'OFFENSIVE', 2 => 'SPAM', 3 => 'IRRELEVANT']

$name_to_enum_object_lookup = array_column(Type::cases(), null, 'name');
// ['OFFENSIVE' => Type::OFFENSIVE, 'SPAM' => Type::SPAM, 'IRRELEVANT' => Type::IRRELEVANT]

$value_to_enum_object_lookup = array_column(Type::cases(), null, 'value');
// [1 => Type::OFFENSIVE, 2 => Type::SPAM, 3 => Type::IRRELEVANT]

Solution 2:[2]

You can also use array_map:

$list = array_map(fn($i) => $i->value, Type::cases());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Amir MB