Array access and modification in PHP - Time & Space Complexity
We want to understand how fast we can get or change items in an array.
How does the time needed change when the array grows bigger?
Analyze the time complexity of the following code snippet.
$array = [1, 2, 3, 4, 5];
// Access the third element
$value = $array[2];
// Modify the first element
$array[0] = 10;
// Add a new element at the end
$array[] = 6;
This code accesses, changes, and adds elements in an array.
Look for any repeated steps or loops.
- Primary operation: Single direct access or modification of an array element.
- How many times: Each operation happens once, no loops or recursion.
Accessing or changing one item takes the same time no matter how big the array is.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays the same even if the array grows larger.
Time Complexity: O(1)
This means accessing or changing one element takes a constant amount of time, no matter the array size.
[X] Wrong: "Accessing an element takes longer if the array is bigger."
[OK] Correct: Arrays let us jump directly to any element by its position, so the time does not grow with size.
Knowing that array access and modification are fast helps you choose the right data structure and explain your code clearly.
"What if we searched for a value without knowing its position? How would the time complexity change?"