0
0
PHPprogramming~5 mins

Type declarations for parameters in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Type declarations for parameters
O(n)
Understanding Time 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?

Scenario Under Consideration

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

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

As the array gets bigger, the function checks each number once.

Input Size (n)Approx. Operations
10About 10 additions
100About 100 additions
1000About 1000 additions

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

Final Time Complexity

Time Complexity: O(n)

This means the time to run the function grows in a straight line with the input size.

Common Mistake

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

Interview Connect

Understanding how type declarations affect performance shows you know both code safety and efficiency, a useful skill in real projects and interviews.

Self-Check

"What if the function also checked the type of each array element inside the loop? How would the time complexity change?"