Why isn't this simple PHP expression working?
$links = array('https://google.com', 'http://aloe.com', 'http://foobar.org/image.jpg');
foreach ($links as 开发者_如何学Go$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?
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 />';
}
}
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.
$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 />";
}
}
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 />';
}
}
精彩评论