Auto populate a select box using an array in PHP

If i had a select box

<select><option>...<option></select>

and I had an array of values from 1-12

using php, how would I auto populate that select box using that array?

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

supposing the array looks like:

$array = array(
  1=>"My first option",
  2=> "My second option"
);

<select>
  <?php foreach($array as $key => $value) { ?>
    <option value="<?php echo $key ?>"><?php echo $value ?></option>
  <?php }?>
</select>

Solution 2

You could make your own simple function as below:

function generateSelectFromArray($array){
  // echo your opening Select
  echo "<select>";
  // Use simple foreach to generate the options
  foreach($array as $key => $value) {
    echo "<option value=' $key '> $value </option>";
   }
   echo "</select>";
}

Usage:

$array = array(
 1=>"My first option",
 2=> "My second option"
);

generateSelectFromArray($array);

Solution 3

There’s no single way to do it but you might do something like:

<select>
<?=getMyOptions()?>
</select>

where getMyOptions() is a function call that retrieves the options (from a database for example) and prints each one in the format

<option value="x">XXX</option>

Personally, I tend to use a generic function which I call printAsOptions(). This function takes an array of objects. It expects that the objects in the array have a field called “id” and a field called “name”. It iterates through the array and prints an option as above for each item. This way, you can create one function for fetching the array of objects (from a database for example) without mixing in presentation logic. The presentation logic is handled by the generic printAsOptions() function.

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply