Input validation and sanitization in PHP - Time & Space 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.
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 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.
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 |
|---|---|
| 10 | About 10 times the work |
| 100 | About 100 times the work |
| 1000 | About 1000 times the work |
Pattern observation: The work increases evenly as input size increases.
Time Complexity: O(n)
This means the time to clean inputs grows directly with the number of inputs.
[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.
Understanding how input validation scales helps you write secure and efficient code, a skill valued in many coding challenges and real projects.
"What if we added nested arrays inside inputs? How would the time complexity change?"