0
0
PHPprogramming~5 mins

Compact and extract functions in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Compact and extract functions
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run PHP's compact and extract functions changes as the number of variables grows.

How does the work inside these functions grow when we add more variables?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$var1 = 10;
$var2 = 20;
$var3 = 30;

// Create an array from variables
$array = compact('var1', 'var2', 'var3');

// Extract variables back from array
extract($array);
    

This code creates an array from named variables using compact, then restores those variables using extract.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Both compact and extract loop through the list of variable names or array keys.
  • How many times: Once for each variable name given to compact or each key in the array for extract.
How Execution Grows With Input

As the number of variables increases, the functions do more work, roughly one step per variable.

Input Size (n)Approx. Operations
10About 10 steps
100About 100 steps
1000About 1000 steps

Pattern observation: The work grows directly in proportion to the number of variables.

Final Time Complexity

Time Complexity: O(n)

This means the time to run compact or extract grows linearly with the number of variables involved.

Common Mistake

[X] Wrong: "compact and extract run instantly no matter how many variables there are."

[OK] Correct: Both functions must look at each variable name or array key, so more variables mean more work and more time.

Interview Connect

Understanding how built-in functions like compact and extract scale helps you reason about performance in real projects and shows you can think about code efficiency clearly.

Self-Check

"What if we passed an array with nested arrays to extract? How would the time complexity change?"