Multiple select with validation?

I’m trying to make this work. I have an multiple select field and when I hit submit it works just fine. But if I have an validation on my form fields and one filed is missing I show trhe form again with the data allready inserted in the fields except the one which fails validation. All that works just fine but… I wnat to be able to have the selected irems the user has selected preselected when vomming back to the form but cant get it to work…

Here is what I have tryied:


$replace = $_POST['replace'];
echo '<select id="tags" name="replace[]" multiple="multiple">';
		
$results = preg_match_all('~<([^/][^>]*?)>~', $str, $arr); 
$arr = array_unique($arr[1]);

foreach($arr as $arr1=>$value){
	if(!empty($replace)){
		foreach($replace as $rep){
			if($value == $rep){
				echo '<option selected>'.htmlentities('<'.$value.'>').'</option>';
			} else {
				echo '<option>'.htmlentities('<'.$value.'>').'</option>';
			}
		}
	} 
}

echo '</select>';

This comes out with nothing?

How do I go about this?

Thanks in advance…

Pseudocode cause i dont follow your variable structure.


foreach (ItemsInList AS Item) {
  if([FPHP]in_array[/FPHP](Item,SelectedItems)) {
    echo Selected Option
  } else {
    echo Unselected Option
  }
}

Tryid like this:

foreach($arr as $arr1=>$value){
	if(in_array($value,$replace)) {
		echo '<option selected>'.htmlentities('<'.$value.'>').'</option>';
	} else {
		echo '<option>'.htmlentities('<'.$value.'>').'</option>';
	}
}

It doesnt get any results… The checked items is unchecked when comming back?

$replace = $_POST['replace'];
		
foreach($replace as $rep){
	echo 'Replacing; '.htmlentities($rep).'<br>';
}

When running above I get data?

Shouldnt it be “<option selected=‘selected’>” ?

The solution was this:

foreach($arr as $arr1=>$value){
	if(in_array('<'.$value.'>',$replace)) {
		echo '<option selected>'.htmlentities('<'.$value.'>').'</option>';
	} else {
		echo '<option>'.htmlentities('<'.$value.'>').'</option>';
	}
}

It was because of the html tags… Thanks for help…