I have been trying to get PHP to populate HTML multi-select form with pre-selected values based on previous saves done by the user. I found helpful examples here and elsewhere that helped conceptually understand what needs to be done but I cannot get the syntax to work.
Here is the relevant code snippet
<?php
// This array will hold all options to be displayed in multi-select form
$allservices = array('amazon','facebook','twitter','reddit');
// $blockedservices is variable comes as a string from database like amazon,facebook.
// Initially the value of the array is NULL for new users or user that never submitted.
// I am exploding here as array to make it easier to work with like ['amazon','facebook']
$selectedservices = explode(",", $blockedservices);
?><select name="services[]" multiple="multiple"><?
//looping through all options
foreach($allservices as $option){
//trying to see if option was preselected
if($selectedservices == $option) {
?><option selected="selected" value="<?php echo $option;?>"><?php echo $option;?></option><?
}
else {
?><option value="<?php echo $option;?>"><?php echo $option;?></option><?
}
}
?></select>
Currently, this results in Undefined variable: option in...
Update
Based on the feedback, using <?php
instead of just <?
resolves the undefined error issue. However, the pre-selected options are not displaying. Rather, all options are displayed with no pre-selection even when pre-selection exists.
I also tried in_array
with the same result of not identifying the pre-selected option.
Here is another snippet with in_array
:
<?php
$allservices = array('amazon','facebook','twitter','reddit');
$selectedservices = explode(",", $blockedservices);
?><select name="services[]" multiple="multiple"><?php
foreach($allservices as $option){
if(!empty($selectedservices)){
if(in_array($option,$selectedservices)){
?><option selected="selected" value="<?php echo $option;?>"><?php echo $option;?></option><?php
}
else {
?><option value="<?php echo $option;?>"><?php echo $option;?></option><?php
}
}else{
?><option value="<?php echo $option;?>"><?php echo $option;?></option><?php
}
}
?></select>
Update 2
I posted an answer below that addresses all the code and syntax issues. The answer posted works as intended in all browsers. Hope it helps someone needing to accomplish the same thing in the future. Thanks to everyone for the comments that helped along the way.