Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Php code, add a condition to foreach loop

Tags:

foreach

php

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**
            }
like image 698
webmasters Avatar asked Dec 23 '10 09:12

webmasters


3 Answers

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;
    }
}
like image 175
Jan Hančič Avatar answered Oct 02 '22 16:10

Jan Hančič


$site = '1'

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

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

        // ...your code here...
    }
like image 40
Vladyslav at AssuredLabs Avatar answered Oct 02 '22 16:10

Vladyslav at AssuredLabs


Just use an if statement:

foreach($mysites as $mysite) {
    if ($mysite !== $site) {
        echo $mysite;
    }
}
like image 42
fire Avatar answered Oct 02 '22 15:10

fire