In attempting to determine whether a string contains an undesirable element, programmers may encounter unexpected results when utilizing strpos() for direct equality comparisons.
Consider this scenario:
$link = 'https://google.com'; $unacceptables = ['https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png']; foreach ($unacceptables as $unacceptable) { if (strpos($link, $unacceptable) === true) { echo 'Unacceptable Found<br />'; } else { echo 'Acceptable!<br />'; } }
Intriguingly, this code prints "Acceptable!" for each element in $unacceptables, despite https being present in $link. This seemingly paradoxical behavior arises from the nature of strpos() itself.
Delving into the official PHP documentation clarifies the function's true purpose:
Returns the numeric position of the first occurrence of needle in the haystack string.
Therefore, when comparing the result of strpos() directly against true, you effectively check for the existence of the undesirable element in $link, not its equality with true.
To rectify this issue, a more appropriate approach is to utilize !== false in the if statement:
// ... if (strpos($link, $unacceptable) !== false) {
By doing so, you correctly assess whether strpos() has detected the presence of the undesirable element, resulting in the desired outcome.
The above is the detailed content of Why Does Comparing `strpos()` to `true` Fail to Detect String Occurrences in PHP?. For more information, please follow other related articles on the PHP Chinese website!