Unreliable Boolean Comparison in PHP: Understanding the Quirks of strpos()
In PHP, the strpos() function is a fundamental tool for searching within strings. However, a common pitfall that programmers encounter involves comparing the result of strpos() using the strict equality operator (===) against true.
The Issue:
Consider the following code snippet:
$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 />'; } }
This code attempts to check whether the $link URL contains any of the strings listed in $unacceptables. However, it unexpectedly prints "Acceptable!" for all cases, even when "https:" is present in $link.
The Solution:
The root of the issue lies in PHP's behavior for comparing the result of strpos(). By default, strpos() returns an integer representing the position of the first occurrence of the substring within the string. If the substring is not found, it returns false.
In the code snippet, when comparing strpos() against true, you're essentially checking if the result is a number other than zero. Since the function always returns a number when it finds a match, this comparison always returns true, incorrectly indicating the presence of a substring.
To resolve this, use the strict inequality operator (!==) instead, which checks for non-equality. This ensures that the comparison is made against false when the substring is not found.
// ... if (strpos($link, $unacceptable) !== false) {
By following this simple modification, the code snippet will correctly identify and print "Unacceptable Found" when the $link URL contains one of the prohibited substrings.
The above is the detailed content of Why Does Strict Equality with `strpos()` in PHP Often Produce Unexpected Results?. For more information, please follow other related articles on the PHP Chinese website!