Connecting Tech Pros Worldwide Forums | Help | Site Map

I think this is a simple question...

Alexander Ross
Guest
 
Posts: n/a
#1: Jul 17 '05
I have a variable ($x) that can have 50 different (string) values. I want
to check for 7 of those values and do something based on it ... as I see it
I have 2 options:

1) if (($x=="one") || ($x=="two") || ... || ($x=="seven")) ...

or

2) switch ($x){
case("one"):
case("two"):
...
}

It seems that there might be a more efficient way to do this?? Is there?

Alex



matty
Guest
 
Posts: n/a
#2: Jul 17 '05

re: I think this is a simple question...


Alexander Ross wrote:
[color=blue]
> I have a variable ($x) that can have 50 different (string) values. I want
> to check for 7 of those values and do something based on it ... as I see
> it I have 2 options:
>
> 1) if (($x=="one") || ($x=="two") || ... || ($x=="seven")) ...
>
> or
>
> 2) switch ($x){
> case("one"):
> case("two"):
> ...
> }
>
> It seems that there might be a more efficient way to do this?? Is there?
>
> Alex[/color]
You could do
if (pre_match('/^(one|two|three|four|five|six|seven)$/', $x))

but I think a lot of the time the switch method makes for more readable code.
It could be interesting to benchmark which is fastest, although I suspect there
isn't a lot of difference for most applications.

--
Matt Mitchell - AskMeNoQuestions
Dynamic Website Development and Marketing
Ondrej Brablc
Guest
 
Posts: n/a
#3: Jul 17 '05

re: I think this is a simple question...


Andy Hassall wrote:
[color=blue]
> On Mon, 04 Aug 2003 19:05:38 GMT, "Alexander Ross" <alexross@bleen.net> wrote:[/color]
....[color=blue][color=green]
>>It seems that there might be a more efficient way to do this?? Is there?[/color]
>
>
> Put possible values in an array, use array_search, for example.[/color]
....

array_search is for associated arrays, you should use

if (in_array($x, array('one','two',...)))
{

}

Regards,
Ondrej

Closed Thread