However, this isn’t very intuitive. I’d prefer something both more compact and more positive in that it searches for true result, rather than a false one. Something like this:
if (strpos($subject, ','))
{
echo "Comma found!";
}
or
if (strpos($subject, ',') === true)
{
echo "Comma found!";
}
But neither of the latter two examples work. The first (ugly) way mentioned does work, but it relies on identifying a negative result, which I’d like to avoid because it makes the code a littler harder to read.
strpos is supposed to be faster. php.net on strstr:
"If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead. "
It’s because strpos returns the position of the character you’re searching for, and in this case it returns 0 (because it’s zero-indexed) which PHP interprets as false.
That makes sense. Thanks for clearing that up for me. That’s potentially awkward since 0 evaluates false but 0 could be the position of the str you are searching for.
Still hoping for some cleaner code in anyone has suggestions I’m willing to get away from strpos if it looks cleaner… but I tend to value efficiency over cleanliness. I don’t know about any best practices in this area. I moved to strpos from regex because it is supposed to be 3+ times faster for what I am doing.
The most usual way is strpos(…) !== FALSE, that is how you will (should) see it used most often. I would suggest just getting used to checking that the value does not equal false. However if you really don’t want to use it, then you could use something to check that the returned value is an integer. For example, is_int(strpos(…)).