First-class callable syntax in PHP - Time & Space 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?
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 the loops, recursion, array traversals that repeat.
- Primary operation: Applying the
squarefunction to each element in the array. - How many times: Once for each element in the
$numbersarray (1000 times in this example).
As the number of elements grows, the number of times the function runs grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 function calls |
| 100 | 100 function calls |
| 1000 | 1000 function calls |
Pattern observation: The work grows directly with the number of items; doubling items doubles work.
Time Complexity: O(n)
This means the time to finish grows in a straight line with the number of items you process.
[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.
Understanding how function calls scale helps you explain code efficiency clearly and confidently in interviews.
"What if we replaced array_map with a loop that calls the function manually? How would the time complexity change?"