Typically you can use explode with this, however just using explode is a naive approach as there is a bit of cleanup to be done,
$array = array_filter( array_map('trim', explode(',', $teams ) ) );
This does 3 things.
- explode $teams by comma
- array map, which runs a function against each item, in this case trim which removes whitespace
- array filter which removes empty items just in case you have an item like this
item,,
- note though that array_filter will also remove elements with false
and 0
as well as empty ones, but in this case it should be sufficient.
Now converting the array to your markup should be relativity trivial,
echo '<select name="tournament_team" class="form-control" >';
echo '<option value="">--- Select Team ---</option>';
foreach( $array as $item ){
if($_POST['tournament_team'] == $item){
$selected = ' selected="selected"';
}else{
$selected = '';
}
echo '<option value="'.$item.'"'.$selected.'>'.$item.'</option>';
}
echo '</select>';
There is no need to select the default item, if it's rendered first and there is no selection then it will be selected by default, the $selection
is just for form stickiness and you can omit or modify that as your needs dictate.
Last thing is you'll have to watch the casing here, because you have mixed casing so I am not 100% sure which you want, for example india
vs India
.
To lowercase use strtolower()
to uppercase the first letter only use ucfirst()
Also I haven't tested this but it should be fairly close minus any typos, that I might have made.