Array filter function in PHP - Time & Space Complexity
When we use the array filter function, we want to know how the time it takes changes as the array gets bigger.
We ask: How does filtering more items affect the work done?
Analyze the time complexity of the following code snippet.
$array = [1, 2, 3, 4, 5, 6];
$filtered = array_filter($array, fn($x) => $x % 2 === 0);
print_r($filtered);
This code filters an array to keep only even numbers.
- Primary operation: Checking each element with the callback function.
- How many times: Once for every element in the array.
As the array gets bigger, the number of checks grows in the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to filter grows in a straight line with the array size.
[X] Wrong: "Filtering an array is faster than checking every item."
[OK] Correct: The filter must look at each item to decide if it stays, so it takes time proportional to the array size.
Understanding how filtering scales helps you explain efficiency clearly and shows you know how common functions behave with bigger data.
"What if the callback function itself loops over another array for each element? How would the time complexity change?"