Gettype and typeof checks in PHP - Time & Space Complexity
We want to understand how checking a variable's type affects the time it takes to run a program.
How does the time change when we use gettype checks in PHP?
Analyze the time complexity of the following code snippet.
$values = [123, "hello", 3.14, true, null];
foreach ($values as $value) {
if (gettype($value) === "integer") {
echo "$value is an integer\n";
}
}
This code checks each item in an array to see if it is an integer and prints a message if it is.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping through each element in the array and calling gettype on it.
- How many times: Once for each element in the array.
As the number of items in the array grows, the number of type checks grows at the same rate.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 10 type checks |
| 100 | 100 type checks |
| 1000 | 1000 type checks |
Pattern observation: The work grows directly with the number of items, so doubling items doubles the checks.
Time Complexity: O(n)
This means the time to run grows in a straight line with the number of items checked.
[X] Wrong: "Type checks like gettype are slow and add extra loops."
[OK] Correct: Each type check happens once per item inside the existing loop, so it does not add extra loops or multiply work beyond the number of items.
Understanding how simple operations like type checks scale helps you write clear and efficient code, a skill valued in many programming tasks.
"What if we nested another loop inside to check types of elements inside sub-arrays? How would the time complexity change?"