0
0
PHPprogramming~5 mins

Anonymous function syntax in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Anonymous function syntax
O(n)
Understanding Time Complexity

Let's see how the time needed to run an anonymous function changes as we use it in different ways.

We want to know how the number of steps grows when the function is called multiple times.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


$numbers = [1, 2, 3, 4, 5];
$sum = 0;
$add = function($n) use (&$sum) {
    $sum += $n;
};

foreach ($numbers as $num) {
    $add($num);
}

This code defines an anonymous function to add numbers to a sum, then calls it for each number in the list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Calling the anonymous function inside a loop.
  • How many times: Once for each item in the array.
How Execution Grows With Input

Each time we add one more number, the function runs one more time.

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

Pattern observation: The work grows evenly as the list gets bigger.

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows directly with the number of items we process.

Common Mistake

[X] Wrong: "Anonymous functions run slower and add extra hidden loops."

[OK] Correct: The anonymous function itself runs once per call, just like a normal function, so it doesn't add extra repeated work beyond how many times you call it.

Interview Connect

Understanding how anonymous functions behave helps you explain your code clearly and shows you know how function calls affect performance.

Self-Check

"What if the anonymous function contained a loop inside it? How would the time complexity change?"