El Anonimo El Anonimo - 1 year ago 59
PHP Question

How do I retain selected option in a select list with a for loop?

I created a list of countries using the ACF Wordpress plugin. The plugin allows for creation custom post meta fields so each post got an additional meta data namely the country name.

I get the country list with a WP_Query and store it in the


$myquery = new WP_Query($myargs);
if ($myquery -> have_posts()) :
while ($myquery -> have_posts()) :
$myquery -> the_post();
array_push($arr, get_field('country'));

$result = array_unique($arr);

What I would now need is to pick a country and then retain it when the search for the posts with that country meta field returns. (The blue button to the right.)

How do I go about it? So far I’ve tried this:

<select name="countries" id="countries" class="form-control">
for ($i = 0; $i < count($result); $i++) :
$selected = (isset($_POST['countries']) && $result[$i] == $_POST['countries']) ? 'selected' : '';
$selected = ($result[$i] == @$_POST['countries']) ? 'selected' : '';
echo '<option value="' . $result[$i] . '" ' . $selected . '>' . $result[$i] . '</option>';

Which will not retain the country selected. Neither will

$selected = (isset($_GET['country']) && $result[$i] == $_GET['country']) ? 'selected="selected"': '';

On top of this I need to add the ‘all’ value to allow to select all countries:
<option value="all">all</option>
. The ‘all’ value will have to retain too.

BTW could anybody explain the need for
here for me please? I don’t believe there is a need for a
for this app.

The app can be found at http://elanonimo.dp.ua/ Please ignore the green dropdown button.
(The complete WP theme source code is at http://www.filedropper.com/package1467207510)

Answer Source

array_unique($arr) does not reindex the keys of the array, so the for ($i = 0; $i < count($result); $i++) loop does not work. You can either

$result = array_values(array_unique($arr));


foreach ($result as $country) {
    $selected = (isset($_GET['countries']) && $country == $_GET['countries']) ? ' selected' : ''; 
    echo '<option value="' . $country . '"' . $selected . '>' . $country . '</option>', "\n";

Working code: http://phpfiddle.org/main/code/fuy5-6f3c

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download