Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,884 questions

51,810 answers

573 users

How to declare and use enum in PHP

4 Answers

0 votes
enum Status {
    case Pending;
    case Approved;
    case Decline;
}

$status = Status::Pending;
echo $status->name . "\n"; 


if ($status === Status::Approved) {
    echo "The status is approved!";
}

foreach (Status::cases() as $case) {
    echo $case->name . PHP_EOL; 
}



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';
}

$status = Status::Pending;
echo $status->name . "\n"; 


if ($status === Status::Approved) {
    echo "The status is approved!";
}

foreach (Status::cases() as $case) {
    echo $case->name . PHP_EOL; 
}



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';
}

enum Status {
    case Pending;
    case Approved;
    case Decline;

    public function isFinal(): bool {
        return $this === self::Approved || $this === self::Decline;
    }
}

$status = Status::Approved;
echo $status->isFinal() ? 'Yes' : 'No'; 



/*
run:

Pending
Pending
Approved
Decline

*/

 



answered Jun 9, 2025 by avibootz
0 votes
enum Status: string {
    case Pending = 'pending';
    case Approved = 'approved';
    case Decline = 'decline';

    public static function fromValue(string $value): ?self {
        foreach (self::cases() as $case) {
            if ($case->value === $value) {
                return $case;
            }
        }
        return null;
    }
}

$status = Status::fromValue('approved');
echo $status->name; 



/*
run:

Approved

*/

 



answered Jun 9, 2025 by avibootz

Related questions

1 answer 68 views
3 answers 342 views
1 answer 164 views
164 views asked Jan 19, 2017 by avibootz
2 answers 193 views
1 answer 144 views
1 answer 166 views
...