0
0
PHPprogramming~20 mins

Enum backed values in PHP - Practice Problems & Coding Challenges

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

echo Status::Active->value;
AStatus::Active
BActive
Cpending
Dactive
Attempts:
2 left
💡 Hint
Access the string value of the enum case using ->value.
Predict Output
intermediate
2:00remaining
Enum from method with backed values
What will this code output?
PHP
<?php
enum Level: int {
    case Low = 1;
    case Medium = 5;
    case High = 10;
}

$level = Level::from(5);
echo $level->name;
ALevel::Medium
B5
CMedium
DLow
Attempts:
2 left
💡 Hint
The from() method returns the enum case matching the value.
Predict Output
advanced
2:00remaining
What error does this enum code raise?
What error will this PHP code produce?
PHP
<?php
enum Color: string {
    case Red = 'red';
    case Green = 'green';
    case Blue = 'blue';
}

$color = Color::from('yellow');
ANo error, returns null
BValueError
CParseError
DTypeError
Attempts:
2 left
💡 Hint
from() throws an error if the value is not defined in the enum.
🧠 Conceptual
advanced
2:00remaining
Difference between from() and tryFrom() in backed enums
Which statement correctly describes the difference between from() and tryFrom() methods in PHP backed enums?
Afrom() throws an error if no matching value; tryFrom() returns null instead.
Bfrom() returns null if no matching value; tryFrom() throws an error instead.
CBoth methods throw errors if no matching value is found.
DBoth methods return null if no matching value is found.
Attempts:
2 left
💡 Hint
One method is safer and returns null instead of error.
Predict Output
expert
2:00remaining
Output of enum backed values in array map
What is the output of this PHP code?
PHP
<?php
enum Priority: int {
    case Low = 1;
    case Medium = 5;
    case High = 10;
}

$values = array_map(fn($p) => $p->value, [Priority::Low, Priority::High]);
print_r($values);
A
Array
(
    [0] =&gt; 1
    [1] =&gt; 10
)
B
Array
(
    [0] =&gt; Low
    [1] =&gt; High
)
C
Array
(
    [0] =&gt; Priority::Low
    [1] =&gt; Priority::High
)
D
Array
(
    [0] =&gt; 0
    [1] =&gt; 1
)
Attempts:
2 left
💡 Hint
array_map extracts the ->value property from each enum case.