0
0
PHPprogramming~5 mins

Array key and value extraction in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array key and value extraction
O(n)
Understanding Time Complexity

When we extract keys and values from an array, we want to know how the time to do this grows as the array gets bigger.

We ask: How much work does the computer do when it pulls out all keys or values?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$array = ["a" => 1, "b" => 2, "c" => 3];
$keys = array_keys($array);
$values = array_values($array);
    

This code gets all the keys and all the values from an associative array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Traversing the entire array once to collect keys or values.
  • How many times: Each function loops through all elements once, so twice total for keys and values.
How Execution Grows With Input

As the array grows, the work grows in a straight line with the number of elements.

Input Size (n)Approx. Operations
10About 20 (10 for keys + 10 for values)
100About 200 (100 for keys + 100 for values)
1000About 2000 (1000 for keys + 1000 for values)

Pattern observation: The operations grow directly with the number of elements, doubling because keys and values are extracted separately.

Final Time Complexity

Time Complexity: O(n)

This means the time to extract keys and values grows in a straight line with the number of items in the array.

Common Mistake

[X] Wrong: "Extracting keys and values is instant and does not depend on array size."

[OK] Correct: The computer must look at each element to get keys or values, so more elements mean more work.

Interview Connect

Understanding how simple operations like extracting keys and values scale helps you reason about bigger problems and write efficient code.

Self-Check

"What if we extract keys and values together in one loop instead of separately? How would the time complexity change?"