Daniel Daniel - 4 days ago 6
PHP Question

Simple PHP strpos function not working, why?

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

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.

Comments