Reputation: 315
$links = array('https://google.com', 'http://aloe.com', 'http://foobar.org/image.jpg');
foreach ($links as $link)
{
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');
foreach ($unacceptables as $unacceptable)
{
if (strpos($link, $unacceptable) !== false)
{
echo 'not acceptable!<br />';
}
else
{
echo 'acceptable<br />';
}
}
}
The above should output:
not acceptable
acceptable
not acceptable
But instead if outputs this mess:
not acceptable!
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
acceptable
not acceptable!
acceptable
acceptable
acceptable
acceptable
How to get it to work right?
Upvotes: 1
Views: 86
Reputation: 5559
Here is a correction to your code, while maintaining most of the code that you wrote:
$links = array('https://google.com', 'http://aloe.com', 'http://foobar.org/image.jpg');
foreach ($links as $link)
{
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');
$link_is_acceptable = true;
foreach ($unacceptables as $unacceptable)
{
if (strpos($link, $unacceptable) !== false){
$link_is_acceptable = false;
break;
}
}
if ($link_is_acceptable)
{
echo 'acceptable<br />';
}
else
{
echo 'not acceptable!<br />';
}
}
Upvotes: 0
Reputation: 52372
$links = array('https://google.com', 'http://aloe.com', 'http://foobar.org/image.jpg');
foreach ($links as $link)
{
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');
$accept = true;
foreach ($unacceptables as $unacceptable)
{
if (strpos($link, $unacceptable) !== false)
{
$accept = false;
}
}
if ($accept == true) {
echo "Acceptable<br />";
} else {
echo "Not acceptable<br />";
}
}
Upvotes: 0
Reputation: 3611
you want to have only one output per resource, and not one per resource and unacceptable (cartesian product!)
try this:
$isAcceptable = true;
foreach ( $unacceptables as $unaccetable )
{
if (strpos($link, $unacceptable) !== false)
{
$isAcceptable = false;
break; // not acceptable, no more checks needed
}
}
echo ($isAcceptable ? 'acceptable' : 'not acceptable');
instead of your foreach loop.
Upvotes: 1
Reputation: 920
Because you got loop inside a loop (and that's why it outputs 8 * 3 = 24 times). You need to introduce a variable $is_accepted, set the variable inside the inner loop and output the answer inside the outer but not inside the inner loop.
$links = array('https://google.com', 'http://aloe.com', 'http://foobar.org/image.jpg');
foreach ($links as $link)
{
$unacceptables = array('https:','.doc','.pdf', '.jpg', '.jpeg', '.gif', '.bmp', '.png');
$is_accepted = true;
foreach ($unacceptables as $unacceptable)
{
if (strpos($link, $unacceptable) !== false)
{
$is_accepted = false;
}
}
if (!$is_accepted)
{
echo 'not acceptable!<br />';
}
else
{
echo 'acceptable<br />';
}
}
Upvotes: 1