0
0
PHPprogramming~5 mins

First-class callable syntax in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: First-class callable syntax
O(n)
Understanding Time Complexity

We want to understand how using first-class callable syntax affects the time it takes to run PHP code.

Specifically, how does calling a function this way change the number of steps the program takes?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function square(int $n): int {
    return $n * $n;
}

$numbers = range(1, 1000);

// Using first-class callable syntax
$squares = array_map(square(...), $numbers);
    

This code squares each number in an array using first-class callable syntax with array_map.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Applying the square function to each element in the array.
  • How many times: Once for each element in the $numbers array (1000 times in this example).
How Execution Grows With Input

As the number of elements grows, the number of times the function runs grows the same way.

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

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

Final Time Complexity

Time Complexity: O(n)

This means the time to finish grows in a straight line with the number of items you process.

Common Mistake

[X] Wrong: "Using first-class callable syntax makes the function run faster or slower than a normal call."

[OK] Correct: The syntax is just a cleaner way to pass the function; the number of calls and work done stays the same.

Interview Connect

Understanding how function calls scale helps you explain code efficiency clearly and confidently in interviews.

Self-Check

"What if we replaced array_map with a loop that calls the function manually? How would the time complexity change?"