PHPackages                             dovydasbu/enum - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. dovydasbu/enum

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

dovydasbu/enum
==============

Enum helpers

v1.0(1y ago)02MITPHPPHP ^8.1

Since Apr 11Pushed 1y ago1 watchersCompare

[ Source](https://github.com/dovydasbu/enum)[ Packagist](https://packagist.org/packages/dovydasbu/enum)[ RSS](/packages/dovydasbu-enum/feed)WikiDiscussions main Synced 1mo ago

READMEChangelog (1)Dependencies (1)Versions (5)Used By (0)

Enum Traits
===========

[](#enum-traits)

This repository contains a set of reusable PHP traits that extend the functionality of PHP enums. They are designed to help you easily compare enum cases, create enums from key values, and convert enums to array representations.

> **Requirements:** PHP 8.1 or higher (enums are natively supported from PHP 8.1).

---

Available Traits
----------------

[](#available-traits)

### EnumComparison

[](#enumcomparison)

- **Purpose:** Provides a simple method to compare two enum cases.
- **Method:**
    - `is(self $enum): bool`
        Returns `true` if the current enum instance is exactly the same as the provided enum instance.

### EnumFromKey

[](#enumfromkey)

- **Purpose:** Enables creating an enum instance from a given key and value.
- **Method:**
    - `fromKey(string $key, mixed $value): ?self`
        Iterates through all enum cases using `self::cases()`, calls the method defined by `$key` on each case, and returns the enum case if the returned value matches `$value`.
        Throws a `RuntimeException` if no matching case is found.

### EnumToArray

[](#enumtoarray)

- **Purpose:** Provides various methods to convert enum cases to array formats.
- **Methods:**
    - `names(): array`
        Returns an array of the enum case names.
    - `values(): array`
        Returns an array of the enum case values.
    - `toArray(?string $valueMethod = null): array`
        Returns an associative array where keys are enum values.

        - Without a `$valueMethod`, the array keys are enum values and the values are enum names.
        - With a `$valueMethod`, the trait calls that method on each case to get the matching value.
    - `toArrayWithoutKey(?string $valueMethod = null): array`
        Returns a plain array of values.

        - Without a `$valueMethod`, the array contains the enum values.
        - With a `$valueMethod`, the trait calls that method on each case to get the corresponding values.

---

Usage Example
-------------

[](#usage-example)

Below is an example of how you can use these traits with a PHP enum:

```
