How do I retain selected option in a select list with a for loop?
<p>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.</p>

<p>I get the country list with a WP_Query and store it in the <code>$result</code> variable:</p>

<pre><code>$myquery = new WP_Query($myargs);
if ($myquery -&gt; have_posts()) :
    while ($myquery -&gt; have_posts()) : 
        $myquery -&gt; the_post();
        array_push($arr, get_field('country'));
    endwhile;
endif;

wp_reset_postdata();
$result = array_unique($arr);
</code></pre>

<p>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.)</p>

<p>How do I go about it? So far I’ve tried this:</p>

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

<p>Which will not retain the country selected. Neither will </p>

<pre><code>&lt;?php 
    $selected = (isset($_GET['country']) &amp;&amp; $result[$i] == $_GET['country']) ? 'selected="selected"': ''; 
?&gt;
</code></pre>

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

<p>BTW could anybody explain the need for <code>$_POST</code> here for me please? I don’t believe there is a need for a <code>&lt;form&gt;…&lt;/form&gt;</code> for this app.</p>

<p>The app can be found at <a href="http://elanonimo.dp.ua/" rel="nofollow">http://elanonimo.dp.ua/</a> Please ignore the green dropdown button.
(The complete WP theme source code is at <a href="http://www.filedropper.com/package1467207510" rel="nofollow">http://www.filedropper.com/package1467207510</a>)</p>