4

I have this issue with a string:

$val = 'NOT NULL';

if(stripos($val, 'NULL') !== FALSE){
    echo "IS $val";
}

It evaluates fine, but if I use === TRUE as evaluator, things go wrong. The answer eludes me, please help me understand.

Michael Irigoyen
  • 22,513
  • 17
  • 89
  • 131
derei
  • 193
  • 2
  • 4
  • 17
  • 2
    `===` is strict comparison i.e. matches types as well. Since `stripos` returns integer and integer !== boolean `stripos(...) === true` evaluates to `false`. – Leri Aug 22 '13 at 13:56
  • thank you! indeed, it's obvious now... but for some reason, I was stuck in a faulty logic. – derei Aug 22 '13 at 14:04
  • in php integers are also treated as boolean and in case of `strpos` and `stipos` it returns integer (also string offset starts with 0). and `===` is strict comparison i.e. `0` is not equal to `false` and `1 or more` is not equal to `true`. – Shushant Aug 22 '13 at 14:58
  • @punk , i see... it's tricky. So, if I would use `==` as long as offset would be >0, I would get `TRUE`, but if offset =0, I would get a misleading `FALSE`. Now it's clear that only comparing against strict `FALSE`, I can get the true result. – derei Aug 23 '13 at 09:40

3 Answers3

8

If you read the documentation for stripos() you'll find.

Returns the position of where the needle exists relative to the beginnning 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 does not return TRUE. Since you are using strict equality, your condition will never be true.

If you did stripos($val, 'NULL') == TRUE then your code would execute if NULL were found at position 0 - since PHP will do some type-juggling and effectively 0 == (int)true.

The appropriate way to test for existence using stripos() is what you have:

if (stripos($val, 'NULL') !== FALSE){
    echo "IS $val";
} 
Community
  • 1
  • 1
Jason McCreary
  • 71,546
  • 23
  • 135
  • 174
1

The answer is because you are using the strict equality operator. The function itself returns an int (or boolean if the needle is not found). The return value is not equal (in the strict sense, both value and type) to true, which is why the check fails.

Jeff Lambert
  • 24,395
  • 4
  • 69
  • 96
1

Since === and !== are strict comparison operators - !== false is not the same as ===true since, for example, 1!==false is ok (values and types are not equal), but 1===true is not ok (values are equal, but types are not).

This sample indicates the meaning of strict comparison - i.e. not only values matters, but also types of compared data.

Alma Do
  • 37,009
  • 9
  • 76
  • 105