Home >Backend Development >PHP Tutorial >Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?
Unintended Truth: Understanding the Mismatch in strpos() Comparisons
Despite its common use for string searches, the PHP function strpos() has an unconventional behavior when comparing its result to true. To understand this anomaly, let's examine a snippet of code:
$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 />'; } }
Surprisingly, this code prints "Acceptable!" for every element in the $unacceptables array, even though "https:" is present in the $link variable.
To unravel this puzzle, we must delve into the semantics of strpos(). As its documentation states, strpos() returns the "numeric position of the first occurrence" of the $unacceptable string within $link. In this case, strpos() finds "https:" at position 0 and returns 0, which is a truthy value in PHP.
Therefore, the condition in the if statement (strpos($link, $unacceptable) === true) evaluates to true every time because strpos() always returns a numeric position, which is always coerced to a boolean true.
To rectify this, we should use a non-strict comparison operator (!==):
if (strpos($link, $unacceptable) !== false) {
By changing the comparison to "not equal to false," we ensure that the if statement only evaluates to true when strpos() finds a match and returns a non-zero value (i.e., any numeric position other than 0).
The above is the detailed content of Why Does strpos() Comparison with `=== true` Fail in PHP String Searches?. For more information, please follow other related articles on the PHP Chinese website!