Default parameter values in PHP - Time & Space Complexity
We want to see how using default values for function parameters affects how long a program takes to run.
Does having default values change the work the program does as input grows?
Analyze the time complexity of the following code snippet.
function greet($name = "Guest") {
echo "Hello, " . $name . "!\n";
}
for ($i = 0; $i < 5; $i++) {
greet();
greet("User" . $i);
}
This code defines a function with a default parameter and calls it multiple times with and without arguments.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The for-loop runs 5 times, calling the greet function each time.
- How many times: 10 calls total (2 calls per loop iteration times 5 iterations).
Each loop iteration does a fixed number of function calls regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 5 | 10 function calls |
| 10 | 20 function calls |
| 100 | 200 function calls |
Pattern observation: The total work grows directly with the number of loop iterations.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of loop cycles increases.
[X] Wrong: "Using default parameter values makes the function run faster or slower depending on input."
[OK] Correct: The default value is just a fallback and does not add extra work per call; the time depends on how many times the function runs, not on whether defaults are used.
Understanding how default parameters affect time helps you explain function behavior clearly and shows you know what really impacts performance.
"What if the function greet contained a loop that ran based on the length of the name string? How would the time complexity change?"