1

I am trying to do a conditional if statement that checks whether the value of a variable $cat_ID is not equal to 19 or 26 then it should echo my $priceToShow variable.

PHP

if(($cat_id != '19') || ($cat_id !='26')){ 
    echo $priceToShow;
}
dreamweiver
  • 6,002
  • 2
  • 24
  • 39
ngplayground
  • 20,365
  • 36
  • 94
  • 173

3 Answers3

14

If it can be neither 19 nor 26, use an and statement:

if(($cat_ID != '19') && ($cat_id !='26')){ 
    echo $priceToShow;
}

If you have a lot of values to check, use in_array:

$bad_values = array(19, 26, 54);
if (!in_array($cat_ID, $bad_values)) {
    echo $priceToShow;
}

(In this case, strict comparisons are off; you should always cast your data to the type it's expected to be, and then use strict comparison:

$bad_values = array(19, 26, 54);
if (!in_array(intval($cat_ID), $bad_values, true)) {
    echo $priceToShow;
}

)

Waleed Khan
  • 11,426
  • 6
  • 39
  • 70
7

This will always return true

You need to use an AND conjunction

of for more than 2 values use ! in_array()

Edit: Absolutely right @Waygood

if ( ! ( $v == 19 || $v == 26 ) ) {
  // do your thing
}
chim
  • 8,407
  • 3
  • 52
  • 60
  • 2
    demorgans theorum: negate and change operator = OR to != AND e.g. 19 OR 26 -> !=19 AND !=26 http://www.allaboutcircuits.com/vol_4/chpt_7/8.html – Waygood Mar 12 '13 at 12:55
0

It might be better to use !in_array(). That'll make it quicker and simpler to add and remove when/if needed

if (!in_array($cat_id, array('19', '26')))
{
  echo $priceToShow;
}
Michael
  • 11,912
  • 6
  • 49
  • 64