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"){
deleteDatabaseTables();

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 this operator 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 when  still another comparison operator is required somehow. And the semantics is different in depending on the programming language…

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. Ich berate und Konzeptionieren und entwickle mit fast allem, was einen Prozessor hat.

2 comments

  1. Zwölf Jahre später ist ab PHP 8.0 diese Falle dann entschärft worden: Ein Vergleich wie 0==”deleteTable” liefert jetzt wie erwartet “false”.

Leave a Reply