PHP example

How to convert a string to an enum in PHP

8 min read Updated Dec 2026 Runs in an isolated runtime
Quick answer

Declare a backed enum (PHP 8.1+), such as enum Status: string { case Active = 'active'; }, and convert with Status::tryFrom($input), which returns the case or null. Add a default with Status::tryFrom($input) ?? Status::Active. Use Status::from($input) when an unknown value is a bug: it throws a ValueError. To look a case up by its name, loop over Status::cases() and compare ->name.

PHP 8.1 added real enums with the enum keyword. Before that, the usual stand-in was a class full of constants, which gave you names but no type to check against. An enum case is an object, so text from a form, a query string, a database column or a JSON payload has to be converted into one, and that is where the questions start: what happens with an unknown value, why an int-backed enum rejects "abc" with a TypeError, and how to find a case by name when the enum has no values at all. The sections below declare an enum and cover from and tryFrom, numeric strings, lookup by name, listing the cases, a reusable helper, and converting back to a string, then a table to pick from. Each example runs on this page: hit Run, then edit the code and run it again.

1Backed enums: from() and tryFrom()Recommended

A backed enum gives every case a fixed string or int value, written after the colon in the declaration. That value is what you store and receive, and PHP generates two static methods to turn it back into a case. from() throws a ValueError when no case has the value; tryFrom() returns null instead, which pairs with ?? to fall back to a default. Use tryFrom() on anything a user or another system sends you, and from() where a bad value means a bug you want to hear about.

from_tryfrom.php
<?php

// A backed enum: each case has a fixed string (or int) value
enum Status: string
{
    case Active = 'active';
    case Paused = 'paused';
    case Archived = 'archived';
}

// from() returns the matching case
$status = Status::from('paused');
var_dump($status);
var_dump($status === Status::Paused);

// ...and throws ValueError for an unknown value
try {
    Status::from('deleted');
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";
}

// tryFrom() returns null instead of throwing
var_dump(Status::tryFrom('deleted'));

// ?? turns null into a default case
$input = 'unknown';
$status = Status::tryFrom($input) ?? Status::Active;
echo $status->name, "\n";

// Matching is exact, so normalize outside input first
var_dump(Status::tryFrom('Paused'));
var_dump(Status::tryFrom(strtolower(trim(' Paused '))));

Output

Status::from('paused') gives enum(Status::Paused), and it is the same object as Status::Paused, so === is true: each case exists exactly once. The unknown value throws with the message "deleted" is not a valid backing value for enum Status; left uncaught, that ends the script with Fatal error: Uncaught ValueError. tryFrom() gives NULL, and ?? turns 'unknown' into Active. The comparison is exact and case-sensitive: 'Paused' is NULL until strtolower(trim(...)) cleans it up.

2Int-backed enums and numeric strings

Form fields, query strings and CSV cells are always strings, so an int-backed enum often receives "3" rather than 3. Without strict_types, PHP converts a numeric string to an int before the lookup, so that works. The trap is input that is not numeric at all: then even tryFrom() throws a TypeError, because the argument fails the parameter's type check before the method runs. Validate the number first with filter_var(..., FILTER_VALIDATE_INT) and pass a real int.

int_backed.php
<?php

enum Priority: int
{
    case Low = 1;
    case Normal = 2;
    case High = 3;
}

// A numeric string is converted to an int first
var_dump(Priority::from('3'));
var_dump(Priority::tryFrom(' 2 '));
var_dump(Priority::tryFrom('9'));

// A non-numeric string is a TypeError, even with tryFrom()
foreach (['abc', '', '3abc'] as $input) {
    try {
        Priority::tryFrom($input);
    } catch (TypeError $e) {
        echo $e->getMessage(), "\n";
    }
}

// Safe for any string: validate the integer, then look it up
function priorityFrom(string $input): ?Priority
{
    $n = filter_var($input, FILTER_VALIDATE_INT);
    return $n === false ? null : Priority::tryFrom($n);
}

foreach (['3', ' 1 ', 'abc', '', '1.5', '9'] as $input) {
    $priority = priorityFrom($input);
    echo var_export($input, true), ' -> ', $priority?->name ?? 'null', "\n";
}

Output

'3' becomes High, and surrounding spaces are allowed (' 2 ' is Normal). A number with no case, '9', is a normal NULL. But 'abc', the empty string and '3abc' all throw must be of type int, string given, so a bare tryFrom() on a raw query parameter can still crash the request. priorityFrom() returns null for all of them. It also rejects '1.5', which a direct tryFrom('1.5') would turn into Low with a Deprecated: Implicit conversion from float-string "1.5" to int loses precision notice. With declare(strict_types=1); at the top of the file, even Priority::from('3') throws Priority::from(): Argument #1 ($value) must be of type int, string given, so strict code must cast or validate first either way.

3Convert by case name (pure enums)

A pure enum has cases with no values, so it has no from() or tryFrom(); calling one fails with Call to undefined method Suit::from(). The string you hold is the case name, which also happens when a backed enum's names are what got stored. The portable way is to loop over cases() and compare each ->name. Cases are class constants, so constant() works too (check defined() first, or it throws), and PHP 8.3 added the shorter Suit::{$name} syntax for the same lookup.

by_name.php
<?php

// A pure enum: cases have names but no values
enum Suit
{
    case Hearts;
    case Diamonds;
    case Clubs;
    case Spades;
}

// 1. Loop over cases() and compare names (PHP 8.1+)
function suitFromName(string $name): ?Suit
{
    foreach (Suit::cases() as $case) {
        if ($case->name === $name) {
            return $case;
        }
    }
    return null;
}

var_dump(suitFromName('Clubs'));
var_dump(suitFromName('Stars'));

// 2. constant() with the full name; check defined() first
$name = 'Spades';
$full = Suit::class . '::' . $name;
var_dump(defined($full) ? constant($full) : null);

// 3. Dynamic class constant fetch (PHP 8.3+)
var_dump(Suit::{$name});

try {
    $name = 'Stars';
    Suit::{$name};
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}

// Case-insensitive: compare names with strcasecmp()
function suitFromNameIgnoreCase(string $name): ?Suit
{
    foreach (Suit::cases() as $case) {
        if (strcasecmp($case->name, $name) === 0) {
            return $case;
        }
    }
    return null;
}

var_dump(suitFromNameIgnoreCase('hEaRtS'));

Output

The loop returns enum(Suit::Clubs) for a real name and NULL for 'Stars'. Both constant lookups find enum(Suit::Spades), and an unknown name throws an Error with Undefined constant Suit::Stars, which is why the defined() check is there. One catch with the constant route: an enum may also declare ordinary const values, and constant() returns those too, so add an instanceof Suit check or stick with the loop, which only ever sees cases. strcasecmp() makes the lookup ignore case, so 'hEaRtS' finds Hearts. On PHP 8.4 the loop can be array_find(Suit::cases(), fn($c) => $c->name === $name).

4List all cases, values and names

Every enum has a static cases() method that returns all its cases in declaration order. Each case has a name property, and a backed case also has value, so array_column() pulls either one out in a single call, or builds a value-to-name map. That covers validation messages, dropdown options and documentation without repeating the list of allowed strings anywhere else.

list_cases.php
<?php

enum Status: string
{
    case Active = 'active';
    case Paused = 'paused';
    case Archived = 'archived';
}

// cases() returns every case, in declaration order
foreach (Status::cases() as $case) {
    echo $case->name, ' = ', $case->value, "\n";
}

// array_column() reads the value or name property of each case
$values = array_column(Status::cases(), 'value');
echo implode(', ', $values), "\n";
echo implode(', ', array_column(Status::cases(), 'name')), "\n";

// value => name, ready for a <select>
print_r(array_column(Status::cases(), 'name', 'value'));

// The allowed values make a clear error message
$input = 'deleted';
if (Status::tryFrom($input) === null) {
    echo 'Invalid status "', $input, '". Expected one of: ',
        implode(', ', $values), "\n";
}

Output

array_column(Status::cases(), 'value') gives active, paused, archived and the same call with 'name' gives Active, Paused, Archived. With a third argument it keys the result, so the map reads [active] => Active. Because the list comes from the enum itself, adding a case updates the error message (Expected one of: active, paused, archived) on its own. A pure enum has no value, so use 'name' there.

5A reusable fromName() helper on the enum

Enums can have methods, constants, interfaces and traits, so the lookup belongs on the enum rather than in a loose function. A trait with fromName() and tryFromName() mirrors the built-in from()/tryFrom() pair and can be added to any enum with one use line. Instance methods are the place for things like a display label, written with a match on $this. If several enums share such methods, declare them in an interface and have each enum implements it.

from_name_trait.php
<?php

// One trait gives any enum a lookup by case name
trait FromName
{
    public static function tryFromName(string $name): ?static
    {
        foreach (self::cases() as $case) {
            if (strcasecmp($case->name, $name) === 0) {
                return $case;
            }
        }
        return null;
    }

    public static function fromName(string $name): static
    {
        return self::tryFromName($name) ?? throw new ValueError(
            sprintf('"%s" is not a valid name for enum %s', $name, self::class)
        );
    }
}

enum Status: string
{
    use FromName;

    case Active = 'active';
    case Paused = 'paused';

    // An instance method: a label for display
    public function label(): string
    {
        return match ($this) {
            self::Active => 'Running',
            self::Paused => 'On hold',
        };
    }
}

enum Suit
{
    use FromName;

    case Hearts;
    case Spades;
}

var_dump(Status::fromName('paused'));
echo Status::fromName('ACTIVE')->label(), "\n";
var_dump(Suit::tryFromName('spades'));
var_dump(Suit::tryFromName('stars'));

try {
    Suit::fromName('stars');
} catch (ValueError $e) {
    echo $e->getMessage(), "\n";
}

Output

The same trait serves the backed Status and the pure Suit: Status::fromName('paused') gives enum(Status::Paused), 'ACTIVE' finds Active and its label prints Running, and an unknown name returns NULL from tryFromName() or throws "stars" is not a valid name for enum Suit from fromName(), matching the built-in methods' behavior. Inside the trait, self::class is the enum that uses it. The match in label() has no default arm on purpose: a case added later without a label throws an UnhandledMatchError instead of showing the wrong text.

6Enum back to a string, and match

The way back is a property read: ->value for a backed enum (what you save to a database or send in an API) and ->name for the case name. json_encode() writes a backed case as its value. What does not work is treating a case as a string: an enum is an object, it cannot define __toString(), and it never equals its value with ==. To branch on a case, use match, which compares with ===.

enum_to_string.php
<?php

enum Status: string
{
    case Active = 'active';
    case Paused = 'paused';
}

$status = Status::Paused;

// ->value for storage and APIs, ->name for the case name
echo $status->value, "\n";
echo $status->name, "\n";

// json_encode() writes a backed enum as its value
echo json_encode(['id' => 7, 'status' => $status]), "\n";

// A case is an object, not a string
try {
    echo 'Status: ' . $status, "\n";
} catch (Error $e) {
    echo $e->getMessage(), "\n";
}
var_dump($status == 'paused');

// match compares cases with ===
echo match ($status) {
    Status::Active => 'Processing orders',
    Status::Paused => 'Orders on hold',
}, "\n";

// Round trip: string -> enum -> string
var_dump(Status::from('active')->value);

Output

->value prints paused and ->name prints Paused. The JSON comes out as {"id":7,"status":"paused"}, so an API response needs no conversion. Concatenating the case throws Object of class Status could not be converted to string, and $status == 'paused' is bool(false), so compare $status->value or, better, the case itself. Adding a __toString() method is not allowed either: the script stops with Fatal error: Enum Status cannot include magic method __toString. A pure enum has only ->name, and json_encode() returns false for it, with json_last_error_msg() reporting Non-backed enums have no default serialization.

7Which should you use?

MethodUnknown inputWorks onBest for
Enum::tryFrom($s) ?? defaultReturns nullBacked enumsUser input, query strings, JSON
Enum::from($s)Throws ValueErrorBacked enumsTrusted data where bad values are bugs
filter_var() + tryFrom()Returns nullInt-backed enumsNumeric strings from forms or CSV
foreach cases(), ->nameReturns nullAll enumsPure enums, stored names, ignoring case
constant() / Enum::{$name}Throws ErrorAll enumsExact names, after defined()
trait fromName()Your choiceAll enumsMany enums needing the same lookup

Frequently asked questions

How do I create an enum in PHP?

Use the enum keyword, available since PHP 8.1. A pure enum lists names only: enum Suit { case Hearts; case Spades; }. A backed enum adds a type and a value per case: enum Status: string { case Active = 'active'; }. Backed enums get from() and tryFrom() for converting values, every enum gets cases(), and enums can have methods, constants and interfaces.

What is the difference between from() and tryFrom() in PHP enums?

Both take a backing value and return the matching case. from() throws a ValueError such as "deleted" is not a valid backing value for enum Status when no case matches, and tryFrom() returns null instead. Use tryFrom($input) ?? Status::Default for outside input and from() when a missing case should stop the program.

Why does tryFrom() throw a TypeError instead of returning null?

On an int-backed enum the parameter is an int, so a string that is not numeric, such as "abc", "" or "3abc", fails the type check before tryFrom() runs: Argument #1 ($value) must be of type int, string given. Numeric strings like "3" are converted, unless the file uses declare(strict_types=1), which rejects every string. Validate with filter_var($input, FILTER_VALIDATE_INT) and pass the int.

How do I get an enum case by its name in PHP?

Loop over Enum::cases() and return the case whose ->name equals the string, or null if none does; use strcasecmp() to ignore case. You can also read the case as a class constant with constant(Suit::class . '::' . $name) after a defined() check, or with Suit::{$name} on PHP 8.3 and later. Both throw Undefined constant for an unknown name.

How do I get all enum values as an array?

Call array_column(Status::cases(), 'value') for the backing values or array_column(Status::cases(), 'name') for the case names. array_column(Status::cases(), 'name', 'value') builds a value-to-name map. cases() returns the cases in the order they are declared.

How do I convert a PHP enum to a string?

Read $case->value on a backed enum, or $case->name for the case name on any enum. A case cannot be cast or concatenated (Object of class Status could not be converted to string) and an enum may not declare __toString(). json_encode() writes a backed case as its value and returns false for a pure enum (Non-backed enums have no default serialization).

How were enums done before PHP 8.1?

With a class of constants, such as final class Status { const ACTIVE = 'active'; const PAUSED = 'paused'; }, plus (new ReflectionClass(Status::class))->getConstants() to list them and in_array($input, $constants, true) to validate. The constants are plain strings, so a function cannot require a Status and any string passes the type check. Code that still runs on PHP 7 or 8.0 needs this pattern or a library; on 8.1 and later, use a native enum.

Run it yourself

Open any of these in the full PHP editor to tweak, run and share.

PHP playground