How to iterate over enum
Asked Answered
C

2

16

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?

Christalchristalle answered 6/6, 2022 at 6:16 Comment(0)
A
38

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

Acetic answered 6/6, 2022 at 6:25 Comment(0)
T
5

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

Treadle answered 6/6, 2022 at 6:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.