0

Hey there. I am writing some PHP that needs to check to see if a inputted value fits in with a whole bunch of options. What's the best way to hold all options to check against? I know that an array would work, but is there anything more efficent for this type of operation?

Kyle Hotchkiss
  • 10,754
  • 20
  • 56
  • 82

2 Answers2

0

Checking if the input is a member of an array is actually a pretty safe and efficient way of securing it. For more complex checks, you may want to consider regular expressions with preg_match. However, regular expressions can easily become complicated. Also, one word of advice: Until you've modified the php interpreter, do not worry about of the efficiency of php commands except for loops and network code.

In many cases, you can actually accept anything and then encode it.

Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469
  • Sweet, thanks for giving me the heads up on the efficiency of PHP. – Kyle Hotchkiss Dec 27 '10 at 20:06
  • That does not mean that php is extremely efficient. I just wanted to warn beginners of vastly overestimating the importance of micro optimizations and mis-estimating the actual speed of primitive commands in any language. Heck, I fall into both traps regularly myself. – phihag Dec 27 '10 at 20:14
0

In PHP, all arrays are actually ordered maps, which means you can check keys really efficiently. All you really need for this is the keys, but I'm not sure how to make this without it. Maybe someone else knows how to make just a set.

// Setting the value to 1 is arbitrary since we're using isset
$valid_input = array('first valid option here' => 1,
                     'second valid option here' => 1,
                     'etc' => 1);

$input = // whatever
if(isset($valid_input[$input])) {
    // input is valid
}

References:

isset()

Arrays

Brendan Long
  • 53,280
  • 21
  • 146
  • 188