why is a strpos that is !== false not true?

走远了吗. 提交于 2020-08-07 07:49:56

问题


Consider the following example:

$a='This is a test';

If I now do:

if(strpos($a,'is a') !== false) {
    echo 'True';
}

It get:

True

However, if I use

if(strpos($a,'is a') === true) {
    echo 'True';
}

I get nothing. Why is !==false not ===true in this context I checked the PHP docs on strpos() but did not find any explanation on this.


回答1:


Because strpos() never returns true:

Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.

Returns FALSE if the needle was not found.

It only returns a boolean if the needle is not found. Otherwise it will return an integer, including -1 and 0, with the position of the occurrence of the needle.

If you had done:

if(strpos($a,'is a') == true) {
    echo 'True';
}

You would have usually gotten expected results as any positive integer is considered a truthy value and because type juggling when you use the == operator that result would be true. But if the string was at the start of the string it would equate to false due to zero being return which is a falsey value.




回答2:


The strpos function returns an integer value on success and false only if the needle was not found in the string. In our case, the string 'This is a test' contains 'is a'. So the test (position)!==false [where position is the first occurence of 'is a'] is different from false in both type and value and will return true.



来源:https://stackoverflow.com/questions/52543130/why-is-a-strpos-that-is-false-not-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!