如何在PHP中从数组填充组合框?

时间:2013-05-28 05:39:56

标签: php html arrays combobox

我希望在php中有一个简单的数组,在html中有一个组合框。

<?php
// Here is my array:
$cars=array("Volvo","BMW","Toyota");
?>

3 个答案:

答案 0 :(得分:1)

试试这个:

<?php
$cars=array("Volvo","BMW","Toyota");

if ($_SERVER['REQUEST_METHOD']==="POST") {
    if (isset($_POST['car'])) {
        if (in_array($_POST['car'],$cars)) {
            echo "You selected ".$_POST['car']."!";
            exit;
        }
    }
}

?>
<DOCTYPE html>
<html>
    <form method="post" action="">
        <select name="car">
        <?php
        foreach ($cars as $car) {
            echo '<option value="'.$car.'">'.$car.'</option>';
        }
        ?>
        </select>
        <input type="submit" value="Select">
    </form>
</html>

答案 1 :(得分:0)

试试这个

echo "<select name='cars'>";
foreach($cars as $car)
{
   echo "<option value='".$car."'>".$car."</option>";
}
echo "</select>";

答案 2 :(得分:0)

php页面中的代码:

<?php
$cars=array("Volvo","BMW","Toyota");
$smarty->assign('cars', $cars);
?>

HTML页面的Smarty代码(模板页面):

<select name="car">
  {foreach from=$cars item=car}
    <option value="{$car}">{$car}</option>
  {/foreach}
</select>