4

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.

Pete
  • 105
  • 1
  • 9
  • http://php.net/manual/en/function.strpos.php – Salvatore Q Zeroastro Sep 27 '18 at 18:32
  • if you were to take `=== true` out, you'd get your "true" statement, because `strpos` would return a 1 and not a zero -- IE `if(strpos($a,'is a'){` – Zak Sep 27 '18 at 18:33
  • 1
    The `===` is looking for a `bool` set to `true` -- And while a 1 is *technically* `true` -- It's not *literally* `true` --- And `===` is looking for a *literal* comparison – Zak Sep 27 '18 at 18:38
  • Pete, does @Zak's message make sense to you? I think your question shows that you might be struggling with truthy vs true and falsy vs false. – Michael W. Sep 27 '18 at 18:47
  • Yes, I think I did not know that a positive integer (which is was strpos delivers if it finds the string) does not equate to true in the === sense but only in the == sense. Eventually Barmar's reply to my comment in the answer below about type conversions cleared it up. This should really be in the php manual on strpos. – Pete Sep 27 '18 at 21:40

2 Answers2

7

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.

Community
  • 1
  • 1
John Conde
  • 217,595
  • 99
  • 455
  • 496
0

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.

Gratien Asimbahwe
  • 1,606
  • 4
  • 19
  • 30