0
0
PHPprogramming~20 mins

Enums in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
PHP Enum Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of backed enum value access
What is the output of this PHP code using backed enums?
PHP
<?php
enum Status: string {
    case Pending = 'pending';
    case Completed = 'completed';
}

echo Status::Completed->value;
Apending
BCompleted
CStatus::Completed
Dcompleted
Attempts:
2 left
💡 Hint
Access the string value of the enum case using ->value.
Predict Output
intermediate
2:00remaining
Output of enum method call
What does this PHP code print when calling a method inside an enum?
PHP
<?php
enum Direction {
    case North;
    case South;
    case East;
    case West;

    public function opposite(): Direction {
        return match($this) {
            Direction::North => Direction::South,
            Direction::South => Direction::North,
            Direction::East => Direction::West,
            Direction::West => Direction::East,
        };
    }
}

echo Direction::East->opposite()->name;
AEast
BWest
CNorth
DSouth
Attempts:
2 left
💡 Hint
The opposite of East is West according to the match expression.
🔧 Debug
advanced
2:00remaining
Identify the error in enum declaration
What error does this PHP code raise when declaring this enum?
PHP
<?php
enum Color {
    case Red = 1;
    case Green = 'green';
    case Blue = 3;
}
AFatal error: Backed enum cases must have the same scalar type
BNo error, code runs fine
CTypeError: Enum case values must be integers
DSyntax error: Missing semicolon after case
Attempts:
2 left
💡 Hint
Backed enums require all cases to have the same scalar type.
📝 Syntax
advanced
2:00remaining
Which option causes a syntax error?
Which of these enum declarations will cause a syntax error in PHP?
Aenum Status: string { case Active = 'yes'; case Inactive = 'no'; }
Benum Status { case Active; case Inactive; }
Cenum Status { case Active; case Inactive }
Denum Status: int { case Active = 1; case Inactive = 0; }
Attempts:
2 left
💡 Hint
Check for missing semicolons after case declarations.
🚀 Application
expert
2:00remaining
Number of cases in a backed enum
Given this backed enum, how many cases does it contain?
PHP
<?php
enum HttpStatus: int {
    case OK = 200;
    case Created = 201;
    case Accepted = 202;
    case NoContent = 204;
}

$cases = HttpStatus::cases();
echo count($cases);
A4
B0
C5
D3
Attempts:
2 left
💡 Hint
Count the number of case declarations inside the enum.