I think this is a simple question...

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Alexander Ross

    I think this is a simple question...

    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

    #2
    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 - AskMeNoQuestion s
    Dynamic Website Development and Marketing

    Comment

    • Ondrej Brablc

      #3
      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','tw o',...)))
      {

      }

      Regards,
      Ondrej

      Comment

      Working...