I found automatic typecasting can be a bit of a gotcha.


$sText = "this.is.a.test.text";

if ( $pos = strpos($sText, "test") !== FALSE) {

                echo  substr($sText, 0, $pos)."<".substr($sText, $pos,
strlen("test")).">".substr($sText, $pos+strlen("test"));



The code seems logical enough, and the expected result would be:



In fact it ends up being:



The reason is $pos is typecast as TRUE, not int 10, presumably because it's
in the same scope as the boolean test.

Then when $pos is later used as an int it's converted from TRUE to 1.


You have to bracket the $pos setting to move it into its own scope to
prevent it being typecast:

if ( ($pos = strpos($sText, "test")) !== FALSE) {


No doubt it's mentioned somewhere in the php manual, I just never came
across it.

Just thought I'd highlight one of the gotchas of auto typecasting for any
other simpletons like me.




Reply via email to