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.
<label for="column1">Variable for Column 1: </label> <br> <form> <select name="cols1" id="cols1"> <?php include 'hi2.php'; $vars = getVars(); foreach($vars as $item){ ?> <option value="<?php echo strtolower($item); ?>"><?php echo $item; ?></option> <?php } ?> </select> </form>
This is what is returned from hi2.php
function getVars() { $toReturn = array(); while ($row = pg_fetch_row($ret)) { $count = count($row); $y = 0; while ($y < $count) { $c_row = current($row); array_push($toReturn, $c_row); next($row); $y = $y + 1; } $i = $i + 1; } return($toReturn);
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
<form> <select name="cols1" id="cols1"> </select>array(22) { [0]=> string(9) "westasian" [1]=> string(15) "populationtotal" [2]=> string(17) "population15total" [3]=> string(14) "dwellingstotal" [4]=> string(20) "averagedwellingvalue" [5]=> string(22) "averagehouseholdincome" [6]=> string(16) "populationage014" [7]=> string(17) "populationage2534" [8]=> string(17) "populationage3544" [9]=> string(17) "populationage5564" [10]=> string(15) "populationage65" [11]=> string(17) "populationage4554" [12]=> string(17) "populationage1524" [13]=> string(10) "southasian" [14]=> string(7) "chinese" [15]=> string(5) "black" [16]=> string(8) "filipino" [17]=> string(13) "latinamerican" [18]=> string(14) "southeastasian" [19]=> string(4) "arab" [20]=> string(35) "coffeerestauranttimhortonsregularly" [21]=> string(10) "postalcode" } </form>
Advertisement
Answer
In PHP you’re setting $toReturn
to be a list of HTML options like:
[ '<option value="test">Test</option>', '<option value="test2">Test2</option>', '<option value="test3">Test3</option>' ]
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:
<form> <select name="cols1" id="cols1"> <?php include 'hi2.php'; $vars = getVars(); foreach($vars as $item){ echo $item; } ?> </select> </form>
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
.
$toReturn = array(); while ($row = pg_fetch_row($ret)) { $count = count($row); $y = 0; while ($y < $count) { $c_row = current($row); array_push($toReturn, $c_row); next($row); $y = $y + 1; } $i = $i + 1; } return $toReturn;
and then your foreach
will work as expected using $item
:
foreach($vars as $item){ echo '<option value="' . strtolower($item) . '">' . $item . '</option>'; }