Tweet |
Hi Guys
I encountered a problem when using strpos .
Here is the code
That code outputs " not found ".
The problem is strpos returns the first position of the needle ( "t" ) in the haystack ( "test" ) you are searching in , and in our example , the first position is 0 , which is being casted to boolean , and so it's false .
So the best practice of using strpos and stripos is to use === ( equal in type and value ) like the following example .
I encountered a problem when using strpos .
Here is the code
<?php if(strpos("test","t") echo "found"; else echo "not found"; ?>
That code outputs " not found ".
The problem is strpos returns the first position of the needle ( "t" ) in the haystack ( "test" ) you are searching in , and in our example , the first position is 0 , which is being casted to boolean , and so it's false .
So the best practice of using strpos and stripos is to use === ( equal in type and value ) like the following example .
<?php $pos = strpos("test","t"); if($pos === false ) echo "not found"; else echo "found"; ?>
3 comments:
Your last example need triple equals, not double. =)
Wrong order of params in examples. In strpos("t","test") you try to find 'test' inside 't'.
Code corrected
Thanks Ellisgl and Humenetskyy :)