phpstrpos

strpos() == false fails to acknowledge match at start of the string


I am trying to get strpos to search string variable $string for the phrase "test" and if it doesn't contain "test" another variable $change is redefined as $string2 (where $change has been defined previously)

if (strpos($string, 'test') == false) {
    $change = $string2;
    break;
}       

But unfortunately it doesn't work.

What is the mistake in the code above?


Solution

  • strpos returns false if it does not find the string, which is equivalent to 0 in a type-unspecific conditional in PHP. Make sure to use the === operator when comparing using strpos.

    if (strpos($string, 'test') === false) {
      $change = $string2;
      break;
    }