0
0
PHPprogramming~5 mins

Input validation and sanitization in PHP - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Input validation and sanitization
O(n)
Understanding Time Complexity

When checking and cleaning user input in PHP, it is important to know how the time needed grows as the input gets bigger.

We want to see how the work done changes when the input size changes.

Scenario Under Consideration

Analyze the time complexity of the following code snippet.


function sanitizeInput(array $inputs): array {
    $cleaned = [];
    foreach ($inputs as $key => $value) {
        $trimmed = trim($value);
        $safe = htmlspecialchars($trimmed, ENT_QUOTES, 'UTF-8');
        $cleaned[$key] = $safe;
    }
    return $cleaned;
}

This code takes an array of user inputs, trims spaces, and converts special characters to safe HTML entities.

Identify Repeating Operations

Identify the loops, recursion, array traversals that repeat.

  • Primary operation: Looping through each input item once.
  • How many times: Once for each input element in the array.
How Execution Grows With Input

As the number of inputs grows, the work grows in a straight line because each input is handled one by one.

Input Size (n)Approx. Operations
10About 10 times the work
100About 100 times the work
1000About 1000 times the work

Pattern observation: The work increases evenly as input size increases.

Final Time Complexity

Time Complexity: O(n)

This means the time to clean inputs grows directly with the number of inputs.

Common Mistake

[X] Wrong: "Sanitizing input is instant no matter how many items there are."

[OK] Correct: Each input needs its own cleaning step, so more inputs mean more work.

Interview Connect

Understanding how input validation scales helps you write secure and efficient code, a skill valued in many coding challenges and real projects.

Self-Check

"What if we added nested arrays inside inputs? How would the time complexity change?"