0
0
PHPprogramming~5 mins

Enum backed values in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Enum backed values
O(n)
Understanding Time 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.

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

As the number of enum cases increases, the time to find a matching value grows roughly in direct proportion.

Input Size (n)Approx. Operations
10Up to 10 checks
100Up to 100 checks
1000Up to 1000 checks

Pattern observation: The number of checks grows linearly with the number of enum cases.

Final Time Complexity

Time Complexity: O(n)

This means the time to find a backed value grows directly with the number of enum cases.

Common Mistake

[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.

Interview Connect

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.

Self-Check

"What if we stored the enum cases in a hash map keyed by value? How would the time complexity change?"