Php代码,为foreach循环添加一个条件

时间:2010-12-23 09:54:20

标签: php foreach

如何使此代码有效? TY!

$site = '1'

    $mysites = array('1', '2', '3', '4', '5', '6');
            foreach($mysites as $mysite) 
            {
            echo $mysites;  **but not the site with value 1**
            }

4 个答案:

答案 0 :(得分:8)

一个简单的if就足够了:

$site = '1';

$mysites = array('1', '2', '3', '4', '5', '6');
foreach($mysites as $mysite) 
{
    if ( $mysite !== '1' )
    {
        echo $mysite;
    }
}

或者如果您不想检查$site变量:

$site = '1';

$mysites = array('1', '2', '3', '4', '5', '6');
foreach($mysites as $mysite) 
{
    if ( $mysite !== $site )
    {
        echo $mysite;
    }
}

答案 1 :(得分:3)

只需使用if声明:

foreach($mysites as $mysite) {
    if ($mysite !== $site) {
        echo $mysite;
    }
}

答案 2 :(得分:3)

$site = '1'

    $mysites = array('1', '2', '3', '4', '5', '6');

    foreach($mysites as $mysite) {
        if ($mysite == $site) { continue; }

        // ...your code here...
    }

答案 3 :(得分:0)

你可以这样做:

$mysites = array('1', '2', '3', '4', '5', '6');
        foreach($mysites as $mysite) 
        {
if($mysite != 1){
        echo $mysite;
}
        }