if(strpos("http://www.example.com","http://www.")==0){ // do work}
I'd expect this to resolve as true, which it does. But what happens when I do
if(strpos("abcdefghijklmnop","http://www.")==0){// do work}
This also passes on php 5 because as far as I can work out the strpos returns false which translates as 0.
Is this correct thinking/behaviour? If so what is the workaround for testing for that a substring is at the beginning of another string?
strpos returns an int or boolean false. the == operator also evaluates 0 to mean false, you want to use the === operator (three equals signs) that also checks that the types being compared are the same instead of just seeing if they can be evaluated to mean the same.
so
0
is a possible return value fromstrpos
when it finds a match at the very beginning. In case if the match is not found it returnsfalse
(boolean). So you need to check the return value ofstrpos
using the===
operator which check the value and the type rather than using==
which just checks value.Yes, this is correct / expected behavior :
strpos
can return0
when there is a match at the beginning of the stringfalse
when there is no matchThe thing is you should not use
==
to compare0
andfalse
; you should use===
, like this :Or :
For more informations, see Comparison Operators :
$a == $b
will beTRUE
if$a
is equal to$b
.$a === $b
will beTRUE
if$a
is equal to$b
, and they are of the same type.And, quoting the manual page of
strpos
:===
and!==
compare type and value:I personally tend to use this way :
or
to avoid the "
0
" position then always make it a number more than0
cheers