0

Using php, I tried to check whether a certain string contains some characters.

I used this code, which evaluates to false:

$string1 = 'Hello World!';
if (strpos($string1, 'hel')) {
    echo 'True!';
}

I did a quick google search and found this variation:

$string1 = 'Hello World!';
if (strpos($string1, 'hel') !== false) {
    echo 'True!';
}

Which works and evaluates to true.

What is the actual difference between them and why the first one evaluates as false and the second as true?

Thanks!

omer
  • 23
  • 3
  • 3
    because strpos returns the position, and the position is 0, which when loosely compared evaluates to false as stated in the [documentation](http://php.net/manual/en/function.strpos.php) – billyonecan Jul 26 '18 at 08:37
  • 1
    Just to let you know, your second example is false also. https://3v4l.org/ThGr5 strpos is case sensitive. – Andreas Jul 26 '18 at 08:42

1 Answers1

0

Strpos returns the position of the first letter of the needle.
In your case that is the h in "hello" at position 0.

Since typcasting is enabled in php, 0 is the same as false.
Thus the first is false because the "h" is at the 0 position of the "hello world" string

Andreas
  • 23,610
  • 6
  • 30
  • 62
  • @Saral In what way does that make my answer wrong or not useful? – Andreas Jul 26 '18 at 09:39
  • @Saral I know, I wrote that in the comments above. But my answer is not about the actual string it's about what strpos returns, what typcasting does and how if() interprests that. Also what OP did was a small typo. I'm quite sure OP made a MVCE which means start from nothing and only write the part of the code that is relevant. And making case errors is very easily done. And the fact that there is a insensitive version of strpos makes your comment and vote even less understandable. – Andreas Jul 26 '18 at 09:51