Boolean type behavior in PHP - Time & Space Complexity
Let's explore how the time it takes to work with Boolean values changes as we use more of them.
We want to see how the program's steps grow when handling many Booleans.
Analyze the time complexity of the following code snippet.
$bools = array_fill(0, $n, true);
$result = true;
foreach ($bools as $b) {
$result = $result && $b;
}
echo $result ? 'All true' : 'Not all true';
This code checks if all Boolean values in an array are true by going through each one.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each Boolean in the array.
- How many times: Exactly once for each Boolean, so n times.
As the number of Booleans increases, the steps to check them all grow in a straight line.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 checks |
| 100 | 100 checks |
| 1000 | 1000 checks |
Pattern observation: The work grows evenly with the number of Booleans.
Time Complexity: O(n)
This means the time to check all Booleans grows directly with how many there are.
[X] Wrong: "Checking Booleans is always instant, so time doesn't grow with more values."
[OK] Correct: Even simple checks take time when repeated many times, so more Booleans mean more steps.
Understanding how simple operations add up helps you explain code efficiency clearly and confidently.
"What if we stopped checking as soon as we found a false value? How would the time complexity change?"