0

I'm passing the variable $words (a string containing the words "someText") to an if-statement. I'm testing whether the variable contains these words, and want to base any further logic of off that.

Weird thing is that the test returns false every time, even though the variable contains the words "someText"!

if ($words == "someText") {
  return "True " . $words;
} else {
  return "False " . $words;
}

The output value is always:

False someText

So the test equates to false, but the variable contains the words "someText"! Why is that?


I should add that I'm using return instead of echo because my cms requires that, and I'm passing the value Older to the $words variable before running the code above.

3 Answers3

1

To test, that the string contains the words, you need to use strstr function:

if (strstr($words, "someText") != false) {
  return "True " . $words;
} else {
  return "False " . $words;
}

http://www.php.net/manual/en/function.strstr.php

user4035
  • 22,508
  • 11
  • 59
  • 94
  • @robooneus No, look at the manual: "Returns the portion of string, or FALSE if needle is not found." This code works, I just tested it. – user4035 Jul 25 '13 at 12:55
  • I will, can't yet, still have to wait a couple of mins according to SO. –  Jul 25 '13 at 12:56
0

Use === operator. 30 characters limit. http://php.net/manual/en/language.operators.comparison.php

Shankar Narayana Damodaran
  • 68,075
  • 43
  • 96
  • 126
Mihai
  • 26,325
  • 7
  • 66
  • 81
0

Maybe you have some extra whitespace in the string that you don't notice in your output, but causes the comparison to fail. Try using trim($olderIsTrue) for the comparison. If that doesn't work, then for debugging purposes, try comparing md5 hashes to see if the strings are in fact one and the same. Also, you might want to use the === operator, which is slightly faster than == and provides a strict comparison.

Grampa
  • 1,623
  • 10
  • 25