I have a multi-select box for country selection. I want to select any countries which are associated, meaning an array I get from the database.
Here's the code I have:
<?php
foreach($countries as $country){
if(!empty($offer_countries)){
foreach($offer_countries as $key => $offer_country){
if(isset($offer_country['country_id']) && ($offer_country['country_id'] == $country['id'])){
echo '<option value="'.$country['id'].'" selected>'.$country['name'].'</option>';
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
}else{
echo '<option value="'.$country['id'].'">'.$country['name'].'</option>';
}
}
?>
The $offer_countries array, looks like this:
Array
(
[0] => Array
(
[country_id] => 1
)
[1] => Array
(
[country_id] => 2
)
[2] => Array
(
[country_id] => 3
)
)
I'm looping all countries to display them, then I have a nested foreach to see if the country is already set, if so, make the option box selected.
The problem with this is that let's say I have 3 items selected, it'll display 3 of the same country, based on the number of items in the array. So if United States should be checked, it'll show it three times, with the last one checked.
Ok, sorry for the looong explanation, it's probably fairly self explanatory, but any help would be awesome!
array_uintersectcould work, but I doubt there'd be a performance improvement in this case.