John Terters
John Terters

Reputation: 13

strpos() == false give unexpected result when needle string exists at start of haystack string

function check($text){
  if(strpos('a', $text) == FALSE && strpos('b', $text) == FALSE){
    echo 'error';
  } else {
    echo 'ok';
  }
}

echo check('text') . "\n";
echo check('asd') . "\n";
echo check('bnm') . "\n";
echo check('test') . "\n";
echo check('abc') . "\n";

live: http://codepad.org/W025YYuH

why this not working? This return:

1 error 2 error 3 error 4 error 5 error

but should be:

1 error 2 ok 3 ok 4 error 5 ok

Upvotes: 1

Views: 139

Answers (3)

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324830

You should use === FALSE instead of == FALSE, as explained in the documentation

Additionally, your arguments are in the wrong order. Again, consult the documentation (or, as some people say, RTM)

Upvotes: 6

Alessandro Minoccheri
Alessandro Minoccheri

Reputation: 35983

Invert the position of the argument, first argument is the string, second argument is what do you search into the string.

strpos ( 'The string to search in' ,'the argument of search' )

Then == would not work as expected because the position of 'a' was the 0th (first) character.

Try this:

function check($text){
  if(strpos($text, 'a') === FALSE && strpos($text, 'b') === FALSE){
    echo 'error';
  } else {
    echo 'ok';
  }
}

echo check('text') . "\n";
echo check('asd') . "\n";
echo check('bnm') . "\n";
echo check('test') . "\n";
echo check('abc') . "\n";

Upvotes: 2

MrCode
MrCode

Reputation: 64536

You have the arfuments the wrong way around, change to:

 if(strpos($text, 'a') === FALSE && strpos($text, 'b') === FALSE){

Also note that you need to check for a boolean false with the identical operator (===)

Upvotes: 1

Related Questions