|The False String|
|Written by Mike James|
|Friday, 03 December 2010|
Page 2 of 2
You might have been wondering about the use of the assignment in the if statement but this is just a red herring.
The problem is caused by the simple fact that not all non-null types are treated as true. In fact the rule is that all values convert to true except for:
Notice that the integer value 0 is equivalent to false. Now consider what happens when the target in our example is "a"
In this case the result of strpos is zero which is what is stored in $result but zero is converted to false and so the message "not found" is displayed.
This may be a well known PHP trap waiting for the beginner but it is also a "feature" that comes back to bite many an advanced programmer who has forgotten the basic type juggling rules for false.
Notice the code extract is behaving exactly as it should it is just that in trying to be compact the programmer hasn't expressed the algorithmic idea correctly.
How should you best fix the problem?
The programmer who originated the code wanted to save it at all costs and so came up with the ingenious idea of simply adding one to the result to avoid the zero result! That is:
This works but... the non-standard position in the string i.e. starting counting from one rather than zero, is another disaster waiting to happen! In addition the resulting code is messy and misleading.
It is much better to write:
This shows exactly what the intention is.
The pattern to adopt to avoid this particular type of problem is fairly easy - always write exactly what you mean and never try to save typing by writing a compact form that relies on implicit type conversion rules.
That is if the condition is "function is false" actually write:
The only exception to this rule is if function is a predicate and only returns true or false. Then no type conversion rules come into play and you are safe to use the Boolean value directly.
There is a very strong argument that automatic type conversion should never apply to convert to Boolean.
|Last Updated ( Friday, 07 January 2011 )|