Skip to content
Advertisement

fill html dropdown with php array [closed]

I am trying to fill an html dropdown with a php array. Currently, my code creates an empty dropdown and then prints the array on the screen under the dropdown. Below is the html.

JavaScript

This is what is returned from hi2.php

JavaScript

When replacing the contents of the foreach loop to var_dump($vars); die(); This is the output of the array being printed under the dropdown after inspecting element in the browser

JavaScript

Advertisement

Answer

In PHP you’re setting $toReturn to be a list of HTML options like:

JavaScript

so in your foreach loop you only need to output the value – you don’t need to output the <option ...> in HTML again. Change your first script to the following:

JavaScript

Note: technically in hi2.php you’re not using strtolower on the value, so you’ll probably want to add that.

Another way to do this would be to edit your hi2.php script to instead return an array of values instead of the full HTML option.

JavaScript

and then your foreach will work as expected using $item:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement