This question already has an answer here:
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!
</div>
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