Create php array from select options

There are many ways to create a dropdown select options list from a given array in any programming language like PHP. Please check how to create a select list from a PHP array. However in this case I will make a note of the steps I usually follow to create a PHP array from a given HTML of select list options.

For example I have the following HTML, a very short list of options though.

[php]<select name="fraction[4]" id="id_fraction_4">
<option value="0.0" selected="selected">None</option>
<option value="1.0">100%</option>
<option value="0.9">90%</option>
</select>[/php]

To quickly convert it into a PHP array, I would do the following steps in EditPlus. One can try same steps in any text editor which supports search-replace feature.

Ok here is the ordered list of steps

  1. First of all, remove <select> open and close tags.
  2. Next replace <option value= with null character (empty) by doing search replace.
  3. Next replace </option> with “,
  4. Replace > with =>”
  5. Check if there is selected=”selected” with any option. If it is there remove it manually
  6. Add array( to the very start of your string and ) to the very end. You php array is ready!!

Leave a Reply