Search code examples
phpstrpos

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


Solution

  • 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";