0

Hi I´m trying to put an array into option input. But the problem is I get one blank option. I want to remove it.

Here is what I'm trying to do:

<select name "x">
$myarray=array('black','blue','brown');
for ($i=0;$i<=count($myarray);$i++){
    if ( $row['colur']==$myarray[$i]) {//if value in database = array$i
        echo"<option value='$myarray[$i]' selected>$myarray[$i]</option>";
    } else {
        echo"<option value='$myarray[$i]'>$myarray[$i]</option>";
    }
}

chuff
  • 5,846
  • 1
  • 21
  • 26
Poramat Fin
  • 121
  • 1
  • 10
  • 1
    Additional issues with your code (though not answer-worthy): ``. Judging by the fact that you were able to display options at all, I'm guessing that some spaces/characters were lost in the copy/paste process? – Chris Forrence Aug 13 '13 at 15:42
  • http://stackoverflow.com/questions/3507042/if-block-inside-echo-statement to condense your code a bit more –  Aug 13 '13 at 15:51

2 Answers2

4

You should loop one item less:

for ($i=0;$i < count($myarray);$i++) {

The last $i your loop "sees" is count($myarray) which is 3 in your case. However, because arrays are zero-indexed, item $myarray[3] doesn't exist (it goes from 0 to 2). The if fails and $myarray[3] is shown, which doesn't exist: you also get an error of level "notice" in your server logs (which should be the trigger to find this all out yourself).

To prevent all this, use foreach:

foreach ($myarray as $color) {
    // use $color instead of $myarray[$i]
}
Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195
2

As array index start from 0 to (array length -1), you should mention your for loop accordingly i.e

$array_length = count($myarray);

for ($i=0;$i < $array_length;$i++) {
//your code
}
Sumoanand
  • 8,835
  • 2
  • 47
  • 46