Reputation: 473
I have a php variable ($list
) that is a list of values separated by commas. I am trying to figure out how to convert or input this variable into a HTML select tag. Here is what I have so far:
$dbquery = @$db->query('SELECT * FROM Company');
while ($queryText = $dbquery->fetchArray()){
$array[]=$queryText['Company_Name'];
}
//the next batch of code, which is not included, converts the $array[] into a variable named $list//
//the values for $list are: Company1, Company2, Company3, Company4...//
//HTML select tag//
echo '<select name="testSelect" id="testId">';
echo '<option value="'.$list.'">'.$list;
echo '</option></select>';
I understand that I would need a loop like a "while" or a "for" to list the values within $list, but I am not sure of the exact syntax. Can anyone assist me with this?
Thanks,
DFM
Upvotes: 1
Views: 8594
Reputation: 7484
See implode()
You can simulate the implode() function with a loop and string concatenation.
For example:
$out = '';
$append = ', ';
for($arr as $v)
{
$out .= $v.$append;
}
$out = substr($out, 0, (-1) * strlen($append));
Upvotes: 0
Reputation: 813
You could use something like explode()
to put the list of stuff into an array, then loop through that.. something like:
$myArray = explode(",", $list);
echo "<select name=\"testSelect\" id=\"testId\">\n";
for($i = 0; $i < count($myArray); $i++) {
// add each option to select list..
echo "<option>" . $myArray[$i] . "</option>\n";
}
echo "</option>\n";
More on PHP explode()
function:
http://www.php.net/manual/en/function.explode.php
Upvotes: 0
Reputation: 321578
You need to explode()
the list into an array (if you can't use $array
directly for some reason) then do:
$listArray = explode(', ', $list);
echo '<select name="testSelect" id="testId">';
foreach ($listArray as $item)
echo '<option value="'.htmlspecialchars($item).'">'. htmlspecialchars($item) . "</option>\n";
echo '</select>';
Upvotes: 2
Reputation: 65116
Why are you converting the array into a comma separated list in the first place? Once you have an array you can do
foreach ($company in $list) {
echo '<option value="' . htmlspecialchars($company) . '">' . htmlspecialchars($company) . '</option>';
}
to output your options. If you for some reason really need to have the comma separated list step, you can always use explode(',', $list) to convert it back to an array.
Upvotes: 0
Reputation: 17836
You'll need an option
element for every list item (company name).
<select name="testSelect" id="testId">
<?php foreach ($array as $companyName): ?>
<option value="<?php echo $companyName; ?>"><?php echo $companyName; ?></option>
<?php endforeach; ?>
</select>
Upvotes: 3