views:

525

answers:

5

Hello:

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

+3  A: 

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>
Philippe Gerber
This does what you are after, although it skips the `$list` step (you don't need to create the `$list` variable unless you are using it somewhere else in your code as well.
Blair McMillan
+1  A: 

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>';
Greg
Hello Greg - Thanks; your example worked perfectly.
DFM
A: 

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));
Dor
A: 

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.

Matti Virkkunen
A: 

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

Tim