0

Is there an easy way to implode an array of enums ?

enum Fruits: string{
   case APPLE = 'apple';
   case PEAR = 'pear';
   case ORANGE = 'orange';
}


/*
 * @param array<Fruits>|null $fruits 
*/
function setInDB ( ... $fruits ... ){
   ...
   $str_fruits = implode( ',' $fruits );
   ...
}

My code above makes this PHP error :

Error: Object of class Fruits could not be converted to string

Is there a way to resolve this without make a loop, get enum value and concatenate in string ?

J.BizMai
  • 2,621
  • 3
  • 25
  • 49

1 Answers1

0

You can do so with my library:

https://packagist.org/packages/henzeb/enumhancer

enum Fruits: string {
    use Henzeb\Enumhancer\Concerns\Enhancers;

    case APPLE = 'apple';
    case PEAR = 'pear';
    case ORANGE = 'orange';
}

function setInDB ( Fruits ...$fruits ){
   ...
   $str_fruits = implode( ',', Fruits::of(...$fruits)->values());
   ...
}
SomeOne_1
  • 808
  • 10
  • 10