Home >Backend Development >PHP Tutorial >Why Does `strpos() === true` Give Unexpected Results When Checking for Strings?

Why Does `strpos() === true` Give Unexpected Results When Checking for Strings?

DDD
DDDOriginal
2024-12-29 09:44:16363browse

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!

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