[thelist] PHP question... checking string length

Burhan Khalid thelist at meidomus.com
Sat Mar 26 01:31:47 CST 2005


Jay Blanchard wrote:
> [snip]
> Guys, got a quick question. In PHP, I usually test if a string is empty
> like so:
> 
> if ($myString=='') // do something
> 
> But I recently stumbled upon some code from a much more experienced
> PHP person test empty strings like so:
> 
> if (strlen($myString) == 0) // do something
> 
> Is there any difference/advantage to using one over the other? Only
> apparently one is using the first method should be marginally faster
> (no function call). Thanks!
> [/snip]
> 
> There is no functional difference and the call to the strlen function
> has such a low overhead that my bet would be that you could not discern
> it. One thing to not here, and is just good programming practice all the
> way round, put the test element first ...
> 
> <tip type="good coding practices" author="Jay Blanchard">
> if('' == $myString)
> 
> or
> 
> if(0 == strlen($myString))
> 
> Why? When you are typing code you sometimes make errors. One of those
> most often made is leaving out the additional '=' signs. If you do and
> the code is the other way around the value will be assigned to the
> variable and will not throw an error except perhaps later in the
> conditional or even somewhere else where the variable is expected to be
> something else. Hunting it down can be a PITA and we often look at the
> code and say, "That looks OK". However, with the value first and a
> single operator there will be an error thorwn and you'll know exactly
> where.
> </tip>
> 
> Other things you can use for this test case, isset($myString) or
> empty($myString)

Suprised no one mentioned if ('' === $myString), which is type-safe.


More information about the thelist mailing list