You want to make sure that a valid choice was selected from a drop-down menu generated by the HTML <select/> element.
Use an array of values to generate the menu. Then validate the input by checking that the value is in the array. Example 9-11 uses in_array( ) to do the validation.
Validating a drop-down menu with in_array( )
The menu that Example 9-11 generates is:
<select name='food'> <option>Eggs</option> <option>Toast</option> <option>Coffee</option> </select>
To work with a menu that sets value attributes on each <option/> element, use array_key_exists( ) to validate the input, as shown in Example 9-12.
Validating a drop-down menu with array_key_exists( )
The menu that Example 9-12 generates is:
<select name='food'> <option value='eggs'>Eggs Benedict</option> <option value='toast'>Buttered Toast with Jam</option> <option value='coffee'>Piping Hot Coffee</option> </select>
The methods in Example 9-11 and Example 9-12 differ in the kinds of menus that they generate. Example 9-11 has a $choices array with automatic numeric keys and outputs <option/> elements. Example 9-12 has a $choices array with explicit keys and outputs <option/> elements with value attributes drawn from those keys.
In either case, the validation strategy is the same: make sure that the value submitted for the form element is one of the allowed choices. For requests submitted by well-behaved browsers, this validation rule never fails'web browsers generally don't let you make up your choice for a drop-down menu. Remember, though, that there's nothing requiring that requests to your PHP program come from a well-behaved web browser. They could come from a buggy browser or from a bored 11-year-old with a copy of the HTTP specification in one hand and a command-line telnet client in the other. Because you always need to be mindful of malicious, hand-crafted HTTP requests, it's important to validate input even in circumstances where most users will never encounter an error.
9.5.4. See Also
Documentation on in_array( ) at http://www.php.net/in_array and on array_key_exists( ) at http://www.php.net/array_key_exists.