What are some common pitfalls when using strpos in PHP?
One common pitfall when using strpos in PHP is not checking for strict comparison (===) when evaluating the result. This is because strpos can return 0 if the substring is found at the beginning of the string, which can be falsely interpreted as false in a loose comparison. To avoid this, always use strict comparison when checking the result of strpos.
// Incorrect way to check for substring existence
if (strpos($haystack, $needle)) {
echo "Substring found!";
} else {
echo "Substring not found!";
}
// Correct way to check for substring existence
if (strpos($haystack, $needle) !== false) {
echo "Substring found!";
} else {
echo "Substring not found!";
}