...

View Full Version : Better way to write this if statement



sackstein
11-30-2010, 01:02 AM
Is there a better way to write this? It doesn't seem to work when I dont keep rewriting current_category_id but im sure there is a better way...



if ($current_category_id == 48 || $current_category_id == 52 || $current_category_id == 32)

mlseim
11-30-2010, 01:55 AM
What you typed is correct ... and the only way it will work.

If you have a lot of possible values, you would compare the variable to an array of possible values ... like this:


<?php

// set a value for testing it out.
$current_category_id=32;

// here is a list of possible values that make it "true"
$possible=array(48,52,32,10,77,98,37,22,12);
$flag=0;
foreach($possible as $value){
if($current_category_id == $value){
$flag=1;
}
}

// 0=false ... 1=true
echo $flag;
?>



in this example, the value is 1 (true).



.

MattF
11-30-2010, 02:08 AM
There's the in_array method too, which makes it just a tad simpler.



<?php

// set a value for testing it out.
$current_category_id=32;

// here is a list of possible values that make it "true"
$possible=array(48,52,32,10,77,98,37,22,12);

if (in_array($current_category_id, $possible))
{
}

sackstein
11-30-2010, 07:18 AM
Thanks guys. Its only for 4 values right now but i was curious what I would do in the future if I needed more. That makes sense.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum