0
0
PHPprogramming~5 mins

Array filter function in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Array filter function
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations
  • Primary operation: Checking each element with the callback function.
  • How many times: Once for every element in the array.
How Execution Grows With Input

As the array gets bigger, the number of checks grows in the same way.

Input Size (n)Approx. Operations
1010 checks
100100 checks
10001000 checks

Pattern observation: The work grows directly with the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to filter grows in a straight line with the array size.

Common Mistake

[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.

Interview Connect

Understanding how filtering scales helps you explain efficiency clearly and shows you know how common functions behave with bigger data.

Self-Check

"What if the callback function itself loops over another array for each element? How would the time complexity change?"