Can you expect a mature language that has been around for 13 years, and powering many web sites to do basic string comparison properly? No, not really!!
Run the above code and see for yourself! It will match $toFind with $x!! I got hit with this nasty surprise when calling the array_search() function for a programming contest problem. It appears like PHP is truncating these strings, which it thinks are numbers and comparing the first few characters. Can anyone give a logical explanation of what’s going on? Am I doing something fundamentally wrong, or is PHP hosed?
Update: Jude pointed that using “strict” flag in array_search() uses “===”, and hence gets rid of the problem. But the fundamental question still remains. Why would PHP do an automatic type cast to integer while comparing two strings?
Update 2: The fundamental issue can be traced to this single statement in PHP documentation – “If you compare two numerical strings, they are compared as integers.” This was the root of all problems. I don’t like that behavior, but hey this is PHP. I have a similar gripe with Tcl as well. Try this:
It will print 59, followed by an error ‘expected integer but got “09” (looks like invalid octal number)’ as Tcl treats any string starting with 0 as octal – a tradition it borrows from C, but unfortunately, it overloads the string type!