Maintaining the Select option when validating a form

I have a form with a bunch of <select> fields - most of these have only about 4 <options>. I am first writing the PHP validation and this checks if the user has selected an <option> then it adds the attribute of “selected” to that option. However there are a lot of if statements (the way I am doing it). I have a state field with 50 of the US states and I am wary about adding 50 unnecessary if statements. Guidance is appreciated.

Here’s what I have:

// Validation
if(trim($_POST['state']) === '') {
            $stateError = 'Please select your state.';
            $hasError = true;
        } else {
            $state = trim($_POST['state']);

<option value="Alaska" <?php if($state=="Alaska") echo(" selected=\\"selected\\"");?>>Alaska</option>

First off, writing all those statements for each state would be a pain, second I am not sure about all those if statements. How would a pro handle this? Teach me!

Declare an array of states.
Foreach States as State
Echo Option, if State === Selected, echo selected=“selected”

Programming rule of thumb: If you’re going to do something more than 3 times, reduce it. In this case, 50 Options becomes 4 lines of code.

Something like:
<option value=“Alaska” <?php ($state==trim($_POST[‘state’])) ? echo(“selected=\“selected\””) : ‘’;?>>Alaska</option>

would solve right away.


In cases like this I’m usually a fan of @StarLion’s example.

@StarLion, can you give me an example. I don’t know enough PHP to grasp that concept. An example would work great!

$states=array('AAA','BBB','CCC'); //Your array of States
$sel='BBB'; //The value retrieved from the form
<select name="state">
foreach ($states as $state) {
	$opt='<option value="'.$state.'"';
	if ($sel==$state) { $opt .= ' selected="selected"'; }
	$opt .= '>'.$state.'</option>';
	echo $opt;

siteguru - thanks for that. I think this is a good lesson in arrays in general. I appreciate you doing that. Ill have to give it a shot when I get home.