Cindy
Cindy

Reputation: 11

Exclude Items in a foreach

I have an array, which contents are shown by a foreach. This is my Code:

foreach($ga->getResults() as $result)
{
  if ($result->getdayOfWeek() != 5 || $result->getdayOfWeek() != 6):
    echo $result->getdayOfWeek().'<br>';
  endif;
}

I want to exclude Itmes where $result->getdayOfWeek() is 5 oder 6. The way I have it does not work.

Upvotes: 1

Views: 6593

Answers (1)

Gazler
Gazler

Reputation: 84140

You need an and (&&) instead of an or (||).

foreach($ga->getResults() as $result)
{
  if ($result->getdayOfWeek() != 5 && $result->getdayOfWeek() != 6):
    echo $result->getdayOfWeek().'<br>';
  endif;
}

You could also do it the following way:

foreach($ga->getResults() as $result)
{
  if ($result->getdayOfWeek() == 5 || $result->getdayOfWeek() == 6):
    continue;
  endif;
  echo $result->getdayOfWeek().'<br>';
}

Also, as nikic mentions, the convention is using braces for your if statements:

  if ($result->getdayOfWeek() == 5 || $result->getdayOfWeek() == 6)
  {
    continue;
  }

Upvotes: 6

Related Questions