Home > Enterprise >  How to iterate over enum
How to iterate over enum

Time:06-06

I want to iterate over enum:

enum Shapes
{
    case RECTANGLE;
    case SQUARE;
    case CIRCLE;
    case OVAL;
}

I get Shapes const not defined if I do this:

foreach (Shapes as $shape) { }

The best solution I came with is to manually create array for enum:

$shapes = [
    Shapes::RECTANGLE,
    Shapes::SQUARE,
    Shapes::CIRCLE,
    Shapes::OVAL,
];
foreach ($shapes as $shape) { }

Is there any better way to iterate over the enum?

CodePudding user response:

You can generates a list of cases on an enum with cases() like this:

enum Shapes
{
    case RECTANGLE;
    case SQUARE;
    case CIRCLE;
    case OVAL;
}

foreach (Shapes::cases() as $shape) { 
    echo $shape->name . "\n";
}

The output of this is:

RECTANGLE
SQUARE
CIRCLE
OVAL

for PHP 8.1 and greater.

See: PHP Fiddle

CodePudding user response:

You can try Shapes::cases() ,it returns an array of all cases of a given Enum.

  • Related