3

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.

Is there a mistake in the above?

Thank you.

PiTheNumber
  • 22,828
  • 17
  • 107
  • 180
David Willis
  • 1,082
  • 7
  • 15
  • 23
  • possible duplicate of [Question about strpos in PHP](http://stackoverflow.com/questions/1004897/question-about-strpos-in-php) –  Jul 17 '12 at 03:16

3 Answers3

6

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;
} 
Travis
  • 4,018
  • 4
  • 37
  • 52
3

Try using

if (strpos($string, 'test') === false)

=== instead of ==
Shankar R10N
  • 4,926
  • 1
  • 21
  • 24
3

strpos can return "false" or can return "0" which can be misread as false, so instead of using the == comparison operator (which means "equal to") you have to use === (which means identical to). You might also consider a ternary statement instead of a break:

  $change = (strpos($string, 'test') === false) ? $string2 : $change;
Anthony
  • 36,459
  • 25
  • 97
  • 163