Post Format

Compare Strings with PHP

In my programming work I often switch between different programming languages. It’s not so difficult, but problems sometimes appear just at very simple things.

Strings in PHP are really easy to compare, there is the “==” operator. But there lurks a trap: If either of the operands is not a string, there is an automatic conversation. And that can sometimes be different than the one you expect.

0 == “hello” returns true because “hello” is converted in a number with the value of 0. This gets brisant when the 0 return value was a from function that normally returns a string, and a 0 in case of errors. If the programmer is not aware about it, then the program behaves differently than expected, and precisely in case of errors, which is mostly not as well tested.

$cmd = getCommandFromUser()
if ($cmd == "deleteTable"){

In PHP there is also the operator with three equal signs, “===”. In PHP this first tests whether both operands have the same type.

So you can use thisoperator in such cases. Well, I think that the tripple equal sign is quite a hack, even the double equal sign is mathematically questionable. The === operator is often just put in languages, if somehow still another comparison operator is required,. And the semantics in any programming language is different …

Another possibility is to use strcmp () and strcasecmp (). The second is useful if the upper / lower case letters should be ignored. Bu again you have to be careful: the function returns 0 if the strings are equal, in other contexts the 0 is “False” . So the code again gets confusing:

if (0 == strcasecmp($cmd, "deleteTable")){...}

Author: Karsten Meier

Weil ich gerne Probleme löse bin ich Informatiker geworden. Für meine Kunden berate und konzeptioniere ich und entwickle mit fast allem, was einen Prozessor hat. Sie finden mich auch auf Twitter

One comment

Leave a Reply

Required fields are marked *.