Home >Backend Development >PHP Tutorial >Why Does `strpos() !== true` Fail to Detect String Presence in PHP?

Why Does `strpos() !== true` Fail to Detect String Presence in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 09:59:34171browse

Why Does `strpos() !== true` Fail to Detect String Presence in PHP?

Understanding Numerical Comparisons in strpos()

When performing strict equality comparisons using the strpos() function in PHP, you may encounter unexpected results. This article examines why comparing strpos() with true can lead to the opposite intended outcome.

In the provided code, the if statement compares the result of strpos($link, $unacceptable) with true. However, this comparison fails to achieve its intended purpose of detecting the presence of an undesirable string within $link.

To understand why this happens, we must refer to the strpos() documentation. According to the documentation, strpos() returns the numerical position of the first occurrence of the searched string within the subject string. However, if no occurrence is found, it returns false.

In the code snippet, the if statement checks if strpos() returns true. Since strpos() returns a number (0 or greater) when a match is found and false when there's no match, the statement will always evaluate to false if a match is found. This is because true is considered an invalid number in a strict equality comparison.

To fix this issue, we need to change the comparison operator to !== false, which checks if the result of strpos() is not false (i.e., it found a match):

// ...
if (strpos($link, $unacceptable) !== false) {
    echo 'Unacceptable Found<br />';
} else {
    echo 'Acceptable!<br />';
}
// ...

By using this comparison, the code will correctly identify when one of the unacceptable strings is present in the $link variable and output the appropriate message.

The above is the detailed content of Why Does `strpos() !== true` Fail to Detect String Presence in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn