I am creating an array and then displaying the elements of it with a dropdown using php and html. The array is varying size, so I have a foreach statement to display it, the problem is I can't figure out why the first value in the dropdown is always empty (I want the first value to actually be from my array). Here's the code, any help is much appreciated!

<html>
  <form id="form1" name="form1" method="post" onsubmit="" onreset="" action="thing.php">
<?php

$data = array();
$data[4] = 20.4541;
$data[5] = 32.5631;
$data[6] = 41.9715;
$data[7] = "text";
$data[10] = 2231;
$bestValue = 5;

echo " " . $key;
echo "<select name='dropdown'>";
echo "<option value=''></option>";

if($_POST['dropdown'] !=0){
    foreach($data AS $key=>$value) {
        $sel = '';
        if($key==$_POST['dropdown'] ) {
            $sel = "selected";
        }

        echo "<option value='".$key."' ".$sel.">".$key."</option>"; 
    }}      
else{

    foreach($data AS $key=>$value) {
        $sel = '';
        if($key==$bestValue ) {
                $sel = "selected";
        }
        echo $value;

        echo "<option value='".$key."' ".$sel.">".$key."</option>";             
    }}      

echo "</select>";


foreach($data AS $key2=>$value){
    if($_POST['dropdown'] == $key2){
    echo "  " . $data[$key2] . " degrees";}}
?>

<script>
function submitForm(action)
{
    document.getElementById('form1').action = action;
    document.getElementById('form1').submit();
}
</script>
<center>
<input type="button" onclick="submitForm('thing.php')" value="Find Angle" />
</center>

</html>

As you can see the first value in the dropdown is empty. How do I remove this? Thanks.

share|improve this question

2 Answers

up vote 2 down vote accepted

The first option you are printing is an empty option.

 echo "<select name='dropdown'>";
 echo "<option value=''></option>";

Remove the line

echo "<option value=''></option>";
share|improve this answer
Thank you, as you guys can see I'm new to this. Why is this getting minus on the question? Is this website really so elitist that nooby questions are discouraged? I'm sure you guys were just starting out learning php for the first time at some point too... – Joegramming May 29 '12 at 20:36

Just remove the third echo line.

echo "<option value=''></option>";
share|improve this answer

Your Answer

 
or
required, but never shown
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.