user118779 user118779 - 3 years ago 158
PHP Question

How to get country iso code with country name into select

I am testing a country select, but need 2 values from the array.

  1. country iso code

  2. country name

The var
is now only presenting the country name.

Q: how do I get country iso code also in the select?

function get_europe_multi() {
global $wpdb;
$europe_multi_array = array();
$europe_multi_array = array(
"0" => __('-- Select Country--', 'agent-plugin'),
"AT" => 'Austria',
"BE" => 'Belgium',
"BG" => 'Bulgaria',
"CY" => 'Cyprus',
"CZ" => 'Czech Republic'
return $europe_multi_array ;

$content .= '<form id="form" name="country_select_form_test" method="post" action="">';
$content .= '<select class="select-sme-size" name="country_select[]" id="countries_select">';
foreach(get_europe_multi() as $euData){
$content .= '<option value="'.$euData.'">'. $euData . '</option>';
$content .= '</select><i class="fa fa-check" style="display:none;"></i>';
$content .= '<button type="submit" class="fusion-button button-grey" style="marging-left: 30px;">'. __('test', 'agent-plugin').'</button>';
$content .= '</form>';

Answer Source

PHP's foreach allows you to define a key and value:


foreach (array_expression as $key => $value)

So you just need to update your foreach code block slightly. Based on your data example the country code is the $key and the country name is the $value.

Assuming you want the key as the select value you can use something like this:

foreach(get_europe_multi() as $key => $value) {
     $content .= '<option  value="' . $key . '">' . $value . '</option>';

However, this will allow you to do anything you want with the $key and $value inside your loop.

Here is a working demo:

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