Array count and length in PHP - Time & Space Complexity
When working with arrays in PHP, it's important to know how long it takes to find out how many items are inside.
We want to understand how the time to count items grows as the array gets bigger.
Analyze the time complexity of the following code snippet.
$array = [1, 2, 3, 4, 5];
$count = count($array);
echo "Number of items: $count";
This code counts how many elements are in the array and prints that number.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Accessing the internal size of the array.
- How many times: Constant time; PHP maintains a stored count internally.
As the array gets bigger, counting takes the same time because PHP stores the size internally.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 access |
| 100 | 1 access |
| 1000 | 1 access |
Pattern observation: The number of operations is constant regardless of array size.
Time Complexity: O(1)
This means counting items takes constant time, thanks to PHP's internal size tracking.
[X] Wrong: "Counting items requires checking each element."
[OK] Correct: PHP stores the array size internally, making count() O(1).
Understanding how counting works in constant time helps you explain efficiency clearly in interviews.
"PHP does store the array size internally, making count() O(1). What would the complexity be if it didn't?"