Reputation: 463
I am having problems with strpos evaluating properly.
$status = "L";
$x = strpos($status,'L');
echo var_export($x,true);
echo "<br/>";
if (strpos($status,'L') === true) {echo "L is there!.";}
else {echo "No L Found!";}
This outputs:
0
No L Found!
With how I understand strpos and the "===" vs the "==" this should be finding the L.
What do I not understand?
Upvotes: 0
Views: 180
Reputation: 41810
You do need to perform a strict comparison. You just need to do the opposite one.
if (strpos($status, 'L') !== false) {
echo "L is there!.";
} else {
echo "No L Found!";
}
When evaluated with === true
, strpos($status,'L')
would have to return a literal boolean true
, not just a value that evaluates to true, and as you can see in the documentation, strpos
will never return that.
If you used == true
instead, it would work sometimes, only when L was not the first character in the string. When it is the first character, strpos($status,'L')
will return 0
, which does not evaluate to true
, but any other position in the string would return a positive integer, which does.
Since false
is the value the function returns if the search string is not found, the only reliable way to do this is to do strict comparison against false
.
Upvotes: 0
Reputation: 743
strpos doesn't return true, it returns false if the string isn't found or the index if it is found.
From the official docs:
Returns the position of where the needle exists relative to the beginning of the haystack string (independent of offset). Also note that string positions start at 0, and not 1.
Returns FALSE if the needle was not found.
Upvotes: 4