0
0
PHPprogramming~5 mins

Closures as callbacks in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Closures as callbacks
O(n)
Understanding Time Complexity

We want to understand how the time it takes to run code with closures as callbacks changes when the input grows.

Specifically, how does using a closure inside a function like array_map affect the work done?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$numbers = [1, 2, 3, 4, 5];
$squares = array_map(function($n) {
    return $n * $n;
}, $numbers);

print_r($squares);
    

This code uses a closure as a callback to square each number in an array.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: The closure function is called once for each element in the array.
  • How many times: Exactly as many times as there are elements in the input array.
How Execution Grows With Input

As the array gets bigger, the closure runs more times, once per item.

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

Pattern observation: The work grows directly in proportion to the number of items.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line as the input array gets bigger.

Common Mistake

[X] Wrong: "Using a closure as a callback makes the code slower in a way that changes the time complexity."

[OK] Correct: The closure itself runs once per item, just like a normal function would, so it does not add extra loops or nested work.

Interview Connect

Understanding how closures work as callbacks helps you explain how your code handles repeated tasks clearly and efficiently.

Self-Check

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