1

Hey guys here is my php:

$x = array("one", "two", "three");
foreach ($x as $value)
{
  if ($value != 'one' && $value != 'two')
  {
    echo $value . "<br />";
  }
}

This echo's only the word three. I had to use $value != 'one' && $value != 'two' to make this happen and I was wondering if I could consolidate this into something like this:

if ($value != 'one, two')

That doesn't work so I was wondering if you guys could provide some help.

5 Answers 5

4
if (!in_array($value, array('one', 'two')))
  echo $value;
Sign up to request clarification or add additional context in comments.

Comments

2

You could create a switch statement to make it look prettier, but that's as far as you can go.

switch ($i) {
    case "one":
    case "two":
    case "three":
        echo $value . '<br/>';
        break;
}

Comments

1

if you need to print or do certain operation when value == 'three' then only look for value =='three'

  foreach ($x as $value) 
 {
      if($value === "three")
      echo $value;
 }

also you can take a look at using === operator to compare strings. since == uses type juggling while === enforces same type (2 strings, 2 int no mixing) link: http://www.php.net/manual/en/language.operators.comparison.php

Comments

1

Skip the foreach altogether:

$x=array("one","two","three");
$exclude=array("one","two");

print_r(array_diff($x, $exclude));

Comments

0
if ($value == 'three')

maybe this?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.