简体   繁体   中英

drop-down list showing values multiple times

I have a array in php - array and I am using the follwing code to create a drop-down list for this array -

<html>
<head>
</head>
<body>
<form method="post" action="test.php">
<select name="feature" id="Feature">
        <?php
        $i=0;
        foreach($newFeature as $feat)
        {
            ?>
        <option value="<?php echo $feat;?>"><?php echo $newFeature[$i];?></option>
            <?php
        $i++;
       }
         ?>
</select> <input type="submit" name="submit" value="Test">
</form>
</body>
</html>

The drop-down list contains values twice. Here after traversing the array once and showing the values, code again traverse the value and show them again.

what I am doing wrong here ? please guide.

In my hopinion, you have a little bit confused the foreach with the for loop.

In you case, saying $newFeature[$i] or $feat is actually refering to the same thing.

Therefore, try this:

<html>
<head>
</head>
<body>
<form method="post" action="test.php">
<select name="feature" id="Feature">
        <?php
        foreach($newFeature as $feat)
        {
            ?>
        <option value="<?php echo $feat;?>"><?php echo $feat;?></option>
            <?php
       }
         ?>
</select> <input type="submit" name="submit" value="Test">
</form>
</body>
</html>

Show us the $newFeature array. Also, why do you need the $i variable?

$newFeature[$i]

Here is a more cleaner way to generate the list, also you are using for each in a wrong way.

<form method="post" action="test.php">
    <select name="feature" id="Feature">
    <?php foreach($newFeature as $feat): ?>
        <option value="<?php echo $feat; ?>"><?php echo $feat; ?></option>
    <?php endforeach; ?>
    </select> 
    <input type="submit" name="submit" value="Test">            
</form>

if you are using foreach no need for counting and you should use $feat instead

<?php
foreach($newFeature as $feat)
{
    ?>
<option value="<?php echo $feat;?>"><?php echo $feat;?></option>
    <?php
   }
?>

Using $newFeature[$i] is a wrong way of using foreach loop. please post a snapshot of the array or try the following.

To debug and rectify the issue

  1. Print the $newFeatures array before using the foreach and debug the code.

    Or

2.Add the following line in front of the foreach loop

<?php $newFeature = array_unique($newFeature); ?>

This way might solve your problem. I still recommend you to use the first suggestion and debug your code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM