Open In App

PHP Program to Convert Enum to String

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Enumerations, or enums are a convenient way to represent a fixed set of named values in programming. In PHP, native support for enums was introduced in PHP 8.1. If you are working with an earlier version of PHP, or if you want to explore alternative approaches, you may need a way to convert enums to strings.

1. Using Class Constants

Before PHP 8.1, developers often used class constants to mimic enums. Each constant represents a unique value, and a method can be implemented to convert the enum value to a string.

PHP




<?php
 
class StatusEnum {
    const PENDING = 1;
    const APPROVED = 2;
    const REJECTED = 3;
 
    public static function toString($enumValue) {
        switch ($enumValue) {
            case self::PENDING:
                return 'Pending';
            case self::APPROVED:
                return 'Approved';
            case self::REJECTED:
                return 'Rejected';
            default:
                return 'Unknown';
        }
    }
}
 
// Driver code
$status = StatusEnum::PENDING;
$statusString = StatusEnum::toString($status);
 
echo "Status: $statusString";
 
?>


Output

Status: Pending

Associative Arrays

Another approach is to use associative arrays to map enum values to their string representations. Here, an associative array $stringMap is used for mapping enum values to their string representations.

PHP




<?php
 
class StatusEnum {
    const PENDING = 1;
    const APPROVED = 2;
    const REJECTED = 3;
 
    private static $stringMap = [
        self::PENDING => 'Pending',
        self::APPROVED => 'Approved',
        self::REJECTED => 'Rejected',
    ];
 
    public static function toString($enumValue) {
        return self::$stringMap[$enumValue] ?? 'Unknown';
    }
}
 
// Driver code
$status = StatusEnum::PENDING;
$statusString = StatusEnum::toString($status);
 
echo "Status: $statusString";
 
?>


Output

Status: Pending


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads