Function declaration and calling in PHP - Time & Space 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?
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 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.
Each time we add a new name, the function runs one more time.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 greetings printed |
| 100 | 100 greetings printed |
| 1000 | 1000 greetings printed |
Pattern observation: The work grows directly with the number of names.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of inputs.
[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.
Understanding how function calls add up helps you explain code efficiency clearly and confidently.
"What if the greet function itself had a loop inside? How would the time complexity change?"