0

When it comes to this function, everything seems to work alright

function found($in,$find){
    if(strpos($in,$find) !== false)
        return true;
    else
        return false;
}

if(found("Sample text","text"))
    echo 'Found 1';
if(found("Sample text","house"))
    echo 'Found 2';

Result:

Found 1

But, if I use === I just do not get the right results:

function found($in,$find){
    if(strpos($in,$find) === true)
        return true;
    else
        return false;
}

if(found("Sample text","text"))
    echo 'Found 1';
else
    echo 'Not found';
if(found("Sample text","house"))
    echo 'Found 2';
else
    echo 'Not found';

Result:

Not foundNot found

Both return false

Why is that?

zurfyx
  • 31,043
  • 20
  • 111
  • 145

2 Answers2

4

function strpos() never returns true.

It returns integer being the index of the first occurance of the needle, and if the needle doesn't occur it returns boolean false.

nl-x
  • 11,762
  • 7
  • 33
  • 61
4

=== checks the type as well, strpos returns an integer (except it returns false if the needle was not found) and you are comparing it to boolean true.

halfer
  • 19,824
  • 17
  • 99
  • 186
ka_lin
  • 9,329
  • 6
  • 35
  • 56