Null type and its meaning in PHP - Time & Space Complexity
Let's explore how operations involving the null type affect the time it takes for PHP code to run.
We want to see how the program's work changes when it checks or uses null values.
Analyze the time complexity of the following code snippet.
$values = [null, 1, null, 2, 3, null];
$countNulls = 0;
foreach ($values as $value) {
if (is_null($value)) {
$countNulls++;
}
}
echo $countNulls;
This code counts how many null values are in an array.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each item in the array and checking if it is null.
- How many times: Once for each element in the array.
As the array gets bigger, the program checks more items one by one.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks for null |
| 100 | 100 checks for null |
| 1000 | 1000 checks for null |
Pattern observation: The work grows directly with the number of items.
Time Complexity: O(n)
This means the time to count nulls grows in a straight line as the list gets longer.
[X] Wrong: "Checking for null is instant and does not depend on the list size."
[OK] Correct: Even though checking one item is quick, doing it for many items adds up and takes more time as the list grows.
Understanding how simple checks like null tests scale helps you explain how your code handles data efficiently in real projects.
"What if we changed the array to a nested array and checked for nulls inside each sub-array? How would the time complexity change?"