Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

newbie360's avatar

PHP Enum get all values

<?php

namespace App\Enums;

enum Category: string
{
    case FRUITS = 'fruits';
    case PEOPLE = 'people';

    public static function getValuesA(): array
    {
        return array_map(fn ($category) => $category->value, self::cases());
    }

    public static function getValuesB(): \Illuminate\Support\Collection
    {
        return collect(self::cases())->pluck('value');
    }
}

Which one you prefer, or any PHP buildin method can get all values?

Category::getValuesA(); // PHP native

Category::getValuesB()->toArray();

[
    'fruits', 
    'people'
]
0 likes
4 replies
MikhArt's avatar
MikhArt
Best Answer
Level 2

For me the best approach is to have a separate trait for enums where just one toArray() method is implemented. You can then use this trait in any enum you wish to be able to be treated as an array.

trait Arrayable /*(or something else)*/ 
{
  public static function toArray(): array
  {
    return array_map(
      fn ($item) => $item->value,
      self::cases()
    );
    // or
    return array_column(self::cases(), 'value');
  }
}

Using it in your enum

enum Category: string
{
  use Arrayable;
  ...

Then you can do like this

Category::toArray();
1 like
newbie360's avatar

@MikhArt WOW why i can't think that, that's very cool bro

for you, which one more better

return array_column(self::cases(), 'value'); // PHP native

// or

return collect(self::cases())->pluck('value'); // can use Laravel all collection function
MikhArt's avatar

@newbie360 if you want to use collections then you will need to call all() to get the array of values

return collect(self::cases())
  ->pluck('value')
  ->all();

But IMHO there's no any profit in using collections in this particular case. Better keep it as simple as possible

1 like

Please or to participate in this conversation.