php 5 strpos() difference between returning 0 and false?

Yes, this is correct / expected behavior :

  • strpos can return 0 when there is a match at the beginning of the string
  • and it will return false when there is no match

The thing is you should not use == to compare 0 and false ; you should use ===, like this :

if(strpos("abcdefghijklmnop","http://www.") === 0) {

}

Or :

if(strpos("abcdefghijklmnop","http://www.") === false) {

}

For more informations, see Comparison Operators :

  • $a == $b will be TRUE if $a is equal to $b.
  • $a === $b will be TRUE if $a is equal to $b, and they are of the same type.

And, quoting the manual page of strpos :

This function may return Boolean
FALSE, but may also return a
non-Boolean value which evaluates to
FALSE, such as 0 or "".
Please
read the section on Booleans for
more information.
Use the ===
operator
for testing the return
value of this function.

Leave a Comment