Enum backed values in PHP - Time & Space Complexity
When using enum backed values in PHP, it's important to understand how quickly operations like searching or accessing values happen as the number of enum cases grows.
We want to know how the time to find or use a backed value changes when the enum has more cases.
Analyze the time complexity of the following code snippet.
enum Status: int {
case Pending = 1;
case Active = 2;
case Completed = 3;
case Cancelled = 4;
}
function getStatusName(int $value): ?string {
foreach (Status::cases() as $case) {
if ($case->value === $value) {
return $case->name;
}
}
return null;
}
This code looks through all enum cases to find the name matching a given backed value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through all enum cases with
foreach. - How many times: Once for each enum case, until a match is found or all are checked.
As the number of enum cases increases, the time to find a matching value grows roughly in direct proportion.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | Up to 10 checks |
| 100 | Up to 100 checks |
| 1000 | Up to 1000 checks |
Pattern observation: The number of checks grows linearly with the number of enum cases.
Time Complexity: O(n)
This means the time to find a backed value grows directly with the number of enum cases.
[X] Wrong: "Looking up a backed value in an enum is instant no matter how many cases there are."
[OK] Correct: Because the code checks each case one by one, the time depends on how many cases exist, so it is not instant for large enums.
Understanding how enum backed value lookups scale helps you explain how your code behaves with more data, showing you think about efficiency in real situations.
"What if we stored the enum cases in a hash map keyed by value? How would the time complexity change?"