Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over enum

Tags:

php

enums

php-8.1

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?

like image 431
ICE Avatar asked Dec 05 '25 08:12

ICE


1 Answers

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

like image 87
KIKO Software Avatar answered Dec 07 '25 21:12

KIKO Software



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!