Isset, empty, and is_null behavior in PHP - Time & Space Complexity
We want to understand how checking variables with isset, empty, and is_null affects the time it takes to run PHP code.
How does the time grow when we check many variables?
Analyze the time complexity of the following code snippet.
$values = [null, 0, '', 'hello', false, true];
foreach ($values as $val) {
if (isset($val)) {
echo "isset: yes\n";
}
if (empty($val)) {
echo "empty: yes\n";
}
if (is_null($val)) {
echo "is_null: yes\n";
}
}
This code checks each value in an array using isset, empty, and is_null.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array.
- How many times: Once for each element in the array.
Each check runs once per item, so the total checks grow as the number of items grows.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 30 checks (3 checks x 10 items) |
| 100 | 300 checks (3 checks x 100 items) |
| 1000 | 3000 checks (3 checks x 1000 items) |
Pattern observation: The number of operations grows directly with the number of items.
Time Complexity: O(n)
This means the time to run grows in a straight line as the number of values increases.
[X] Wrong: "isset, empty, and is_null take the same time no matter how many variables we check."
[OK] Correct: Each check runs for every item, so more items mean more total checks and more time.
Understanding how simple checks scale helps you write efficient code and explain your reasoning clearly in interviews.
"What if we replaced the foreach loop with nested loops over two arrays? How would the time complexity change?"