Type declarations for parameters in PHP - Time & Space Complexity
When we add type declarations to function parameters, it helps PHP check the input types. Let's see how this affects the time it takes to run the code.
We want to know: does checking types slow down the function as input size grows?
Analyze the time complexity of the following code snippet.
function sumArray(array $numbers): int {
$total = 0;
foreach ($numbers as $num) {
$total += $num;
}
return $total;
}
$values = [1, 2, 3, 4, 5];
echo sumArray($values);
This function adds up all numbers in an array, using a type declaration to ensure the input is an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for each item in the input array.
As the array gets bigger, the function checks each number once.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 additions |
| 100 | About 100 additions |
| 1000 | About 1000 additions |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to run the function grows in a straight line with the input size.
[X] Wrong: "Adding type declarations makes the function run much slower as the input grows."
[OK] Correct: Type checks happen once per call and do not repeat for each item, so they do not add extra loops or slow down growth with input size.
Understanding how type declarations affect performance shows you know both code safety and efficiency, a useful skill in real projects and interviews.
"What if the function also checked the type of each array element inside the loop? How would the time complexity change?"