Home >Backend Development >PHP Tutorial >Why Does `strpos() === true` Give Unexpected Results When Checking for Strings?
Why Does a Strict Comparison of strpos() to True Yield an Unexpected Result?
Question:
In the given code, the intention is to find any unacceptable string inside the $link variable. However, even when "https" is present in $link, the code prints "Acceptable." What's the reason behind this unexpected behavior?
$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 />'; } }
Answer:
The explanation lies in the nature of the strpos() function. As documented, strpos() returns the numeric position of the first occurrence of $unacceptable within $link. However, in the original code, it's incorrectly compared against true, which has a boolean value. This leads to an unexpected outcome.
To resolve this, the comparison should be modified to check for a non-false value instead. By using !== false, the code will correctly identify any found unacceptable strings.
// ... if (strpos($link, $unacceptable) !== false) {
The above is the detailed content of Why Does `strpos() === true` Give Unexpected Results When Checking for Strings?. For more information, please follow other related articles on the PHP Chinese website!