Search code examples
phpstrpos

Why does strictly comparing strpos() against true give the opposite intended result?


Why isn't this standalone code working:

$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 />';
    }
}

It's printing acceptable every time even though https is contained within the $link variable.


Solution

  • When in doubt, read the docs:

    [strpos] Returns the numeric position of the first occurrence of needle in the haystack string.

    So you want to try something more like:

    // ...
    if (strpos($link, $unacceptable) !== false) {
    

    Because otherwise strpos is returning a number, and you're looking for a boolean true.