webmasters
webmasters

Reputation: 5831

Php code, add a condition to foreach loop

How can i make this code work? TY!

$site = '1'

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

Upvotes: 5

Views: 37509

Answers (4)

Mohammed Abdul Nasser
Mohammed Abdul Nasser

Reputation: 11

you can do this:

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

Upvotes: 0

$site = '1'

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

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

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

Upvotes: 6

Jan Hančič
Jan Hančič

Reputation: 53931

A simple if will suffice:

$site = '1';

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

or if you wan't to check against the $site variable:

$site = '1';

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

Upvotes: 13

fire
fire

Reputation: 21531

Just use an if statement:

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

Upvotes: 3

Related Questions