I am being working on a project where i have a value in table with column "teams" and on that column i have one record with data like this "India, Nepal, Pakistan, Singapore".
In a view page i need to show the column "teams" with one value in a row.
Like this:
<select name="tournament_team" class="form-control" >
<option value=''>--- Select Team ---</option>
<option value='india'>India</option>
<option value='nepal'>Nepal</option>
<option value='pakistan'>Pakistan</option>
<option value='singapore'>Singapore</option>
</select>
How i can get separate value of one column by recognizing it by a comma ?
Thank in advance.
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.
Try explode(string $delimiter, string $string)
explode(",",teams);