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>";
    }
}

2
  • 1
    Additional issues with your code (though not answer-worthy): <select name "x"> -> <select name="x">. 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? Commented Aug 13, 2013 at 15:42
  • stackoverflow.com/questions/3507042/… to condense your code a bit more Commented Aug 13, 2013 at 15:51

2 Answers 2

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]
}
Sign up to request clarification or add additional context in comments.

8 Comments

What is the point of do the count every time? this is a bad practice.
@loops--> Do you have any other ways to suggest me ?
I would use a foreach instead.
How for each is better ? I´ve use both of them but I just aproach with this method as my habbit.
|
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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.