Array key and value extraction in PHP - Time & Space 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?
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 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.
As the array grows, the work grows in a straight line with the number of elements.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 20 (10 for keys + 10 for values) |
| 100 | About 200 (100 for keys + 100 for values) |
| 1000 | About 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.
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.
[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.
Understanding how simple operations like extracting keys and values scale helps you reason about bigger problems and write efficient code.
"What if we extract keys and values together in one loop instead of separately? How would the time complexity change?"