Forum Moderators: coopster

Message Too Old, No Replies

Regrouping variables

Simplifying code

         

encyclo

8:35 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I've got a pretty simple question - I have a code block which echoes a bit of text when a variable has one of several values. However, the code is a bit clunky, and I'm wondering of there is a simpler method.

At the moment I'm doing this:

<?php if ($variable=="abc" OR $variable=="def" OR $variable=="ghi" OR $variable=="jkl") 
echo "text";?>

Is there a better way?

coopster

8:53 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I'll often load an array with valid values and use in_array() [php.net] to validate.
$variable = "abc"; 
$valid_values = array("abc", "def", "ghi", "jkl");
if (in_array($variable, $valid_values)) {
print 'Valid';
} else {
print 'Invalid';
}

hughie

8:57 pm on Sep 13, 2004 (gmt 0)

10+ Year Member



could set the vars as an array and then check to see if the value is in the array.

<?php
$selections=array('abc','def','ghi','jkl');
if (in_array($variable, $selections))
{
echo $text;
}

ta,
hughie

hughie

8:58 pm on Sep 13, 2004 (gmt 0)

10+ Year Member



damn, too late ;-)

coopster

9:03 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



I like the way you think, though ;)

dreamcatcher

10:11 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



or maybe a switch statement?


switch ($variable)
{
case "abc":
//do something;
break;

case "def":
//do something
break;

case "ghi":
//do something
break;

}

encyclo

11:37 pm on Sep 13, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I like the way you think, though ;)

So do I (all of you!) Thanks for the suggestions, guys!