Victor
Victor

Reputation: 17

Cannot make PHP variable option in <select> tag html

I have an array that looks like this:

Array (
    [0] => Array ( [denumireObiect] => Telefon ) 
    [1] => Array ( [denumireObiect] => Laptop ) 
    [2] => Array ( [denumireObiect] => Tableta ) 
    [3] => Array ( [denumireObiect] => Obiect ) 
)

I am trying to take all of those words and make them options for a <select> tag.

This is the code I am using for that:

foreach ($result as $i) {
            echo '<option value = ', $result[$i],'>', $result[$i], '</option>';
          }

This paragraph gives me Illegal offset type error.

This is a var_dump($result) result.

array(4) { 
[0]=> array(1) { 
["denumireObiect"]=> string(7) "Telefon" 
} 

[1]=> array(1) 
{ ["denumireObiect"]=> string(6) "Laptop" } 

[2]=> array(1) {
["denumireObiect"]=> string(7) "Tableta" 
} 

[3]=> array(1) {
["denumireObiect"]=> string(6) "Obiect" } 
} 
...

EDIT:

I have tried doing it like this:

foreach ($result as $i => $val) {
        echo '<option value = ', $i,'>', $i, '</option>';
      }

and it returns 0, 1, 2, 3

Any help is appreciated!

Upvotes: 0

Views: 71

Answers (1)

j4g0
j4g0

Reputation: 198

@WOUNDEDStevenJones made a good point. I have updated my code to make it more readable. Note that you would have to rename the $result variable to $results.

Since every $result from your code is an associative array with the same "denumireObiect" key, you could get the values like this:

foreach ($results as $result) {
    echo "<option value=\"{$result['denumireObiect']}\">{$result['denumireObiect']}</option>";
}

If you do not like using the interpolation you could reformat the echo statement like this:

echo '<option value="' . $result['denumireObiect'] . '">' . $result['denumireObiect'] . '</option>';

or use your format from before :)

Upvotes: 1

Related Questions