0
0
PHPprogramming~5 mins

Default parameter values in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Default parameter values
O(n)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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).
How Execution Grows With Input

Each loop iteration does a fixed number of function calls regardless of input size.

Input Size (n)Approx. Operations
510 function calls
1020 function calls
100200 function calls

Pattern observation: The total work grows directly with the number of loop iterations.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line as the number of loop cycles increases.

Common Mistake

[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.

Interview Connect

Understanding how default parameters affect time helps you explain function behavior clearly and shows you know what really impacts performance.

Self-Check

"What if the function greet contained a loop that ran based on the length of the name string? How would the time complexity change?"