How to get multiple elements from <select> using PHP?

I am creating a theme options page for my WordPress theme, and I would like to have functionality to select multiple items from a list.

The "use one option" that I use looks like this: http://pastie.org/684800 and it works great.

I am new to PHP, so I tried to modify the above code to achieve the result I want. Here is what I came up with: pastie.org/684804. As you can see, I basically added some html values multiple="yes", hoping it will work;)

The code displays the selection item correctly, but it seems to save only the last selection. Can someone please give some advice on how to achieve the preservation of several selected items?

+3
source share
3 answers

If you change the name of the select element to complete it with "[]", PHP will treat it as an array. All selected items will be items in the array. For example:

<select name="myChoices[]" multiple="multiple"> ... </select>

<?php
    $selectedChoices = $_POST['myChoices']; // selectedChoices is an array
?>
+11
source

If you provide a name followed by [] on the form,

 name="my_select[]"

you will get an array in the target php script that you can parse.

+4
source
<select name="mySelection[]" multiple="multiple"> 
  <option></option> 
  <option></option>
  <option></option>
</select>

This will allow you to access multiple selection in php

0
source

Source: https://habr.com/ru/post/1721995/


All Articles