0
0
PHPprogramming~5 mins

Closures in array functions in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures in array functions
O(n)
Understanding Time Complexity

When using closures inside array functions, it is important to understand how the time to run the code grows as the array gets bigger.

We want to know how many times the closure runs and how that affects the total work done.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$array = [1, 2, 3, 4, 5];
$result = array_map(function($item) {
    return $item * 2;
}, $array);
    

This code uses a closure inside array_map to double each number in the array.

Identify Repeating Operations
  • Primary operation: The closure function runs once for each element in the array.
  • How many times: Exactly as many times as there are elements in the array (n times).
How Execution Grows With Input

As the array gets bigger, the closure runs more times, directly proportional to the number of elements.

Input Size (n)Approx. Operations
1010 closure calls
100100 closure calls
10001000 closure calls

Pattern observation: The work grows in a straight line with the input size; doubling the array size doubles the work.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items in the array.

Common Mistake

[X] Wrong: "The closure runs only once, so the time is constant no matter the array size."

[OK] Correct: The closure is called for every element, so more elements mean more calls and more time.

Interview Connect

Understanding how closures work inside array functions helps you explain how your code scales and shows you can reason about performance clearly.

Self-Check

"What if the closure inside array_map called another function that itself loops over the array? How would the time complexity change?"