0
0
PHPprogramming~5 mins

Function declaration and calling in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Function declaration and calling
O(n)
Understanding Time Complexity

When we declare and call a function, we want to know how long it takes as the input changes.

We ask: How does the time grow when we run the function with bigger inputs?

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function greet($name) {
    echo "Hello, $name!\n";
}

$names = ['Alice', 'Bob', 'Charlie'];

foreach ($names as $person) {
    greet($person);
}
    

This code defines a function that prints a greeting and calls it for each name in a list.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

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

Each time we add a new name, the function runs one more time.

Input Size (n)Approx. Operations
1010 greetings printed
100100 greetings printed
10001000 greetings printed

Pattern observation: The work grows directly with the number of names.

Final Time Complexity

Time Complexity: O(n)

This means the time to run grows in a straight line with the number of inputs.

Common Mistake

[X] Wrong: "Calling a function once always takes the same time no matter what."

[OK] Correct: The function might be called many times, so total time depends on how many calls happen.

Interview Connect

Understanding how function calls add up helps you explain code efficiency clearly and confidently.

Self-Check

"What if the greet function itself had a loop inside? How would the time complexity change?"