Last week while I was programming with PHP I ran into a few bumps. I thought I understood the comparison operators in PHP and what NULL was in the language. I was sadly mistaken and it caused me a headache, which led me to write a bunch of truth tests. Yes I know…classic noob mistake. In PHP according to the manual a variable is considered to be null if, it has been assigned the constant NULL, it has not been set to any value yet, or it has been unset(). You would think that an variable with an empty string ( $var = ''; ) would be null but it is not (unless this is a bug, which I’m sure it is not). This was the cause of all the problems I was having.
Let’s cut straight to the chase the following tests will evaluate to be true in PHP.
null is not set null == 0 null == "" "" is set "" == 0 "" == null 0 is set 0 == "" 0 == null
According to my interpretation of the manual it would seem that an empty string null === "" would be true but after testing you can see that it isn’t. Apparently an empty string is considered to be set to a value. I guess a better way to think of NULL is to think of a variable without a type assigned to it yet. The work around is to simply check to see if strlen equals a zero. This works but it calls a function to do it which is a tiny bit slower. I found that using ( isset($var) == true ) && ( $var !== '' ) has the same behavior and is faster. Depending on the variable name it can make your code take up more space making it slightly harder to read. There was only a 0.014 second speed up between using the function and the construct plus the additional comparison. I’ve also considered using empty() but NULL == 0 == "" are all true in PHP.
Update (May 23, 2008)
I thought I would mix it up by creating several tiny articles instead of one large article today.
Update (May 24, 2008)
I found a giant truth test cheat sheet.

0 Responses
Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.