Simple PHP strpos function not working, why?

Daniel picture Daniel · Feb 1, 2011 · Viewed 42.6k times · Source

Why isn't this standalone code working:

$link = 'https://google.com';
$unacceptables = array('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.

Answer

coreyward picture coreyward · Feb 1, 2011

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.