How to make a selection of countries with PHP?

0

Hello good afternoon I'm doing this code to select a country But the problem is that if you selected a country but it gives me the last one of the list how can I show the one I want

function pais ($dato, $name, $select, $tipo){
//--    
    $my_pais = array(
        'de'        => 'Alemania',
        'mx'        => 'Mexico',
        'us'        => 'Estados Unidos',        
    );
//--    
    if ($select){
        echo "<select class=\"height_input data_input_two input__settings\" name=\"".$name."\" id=\"Language\">";
                    foreach ($my_pais AS $my_psais) {
                        echo '<option value="'.$my_psais.'" selected>'.$my_psais.'</option>';

                    }
        echo "</select>";
    }   
//--    
    if ($select){
        //-- 
    }else{
        return str_replace( array_keys($my_pais), array_values($my_pais), $dato);
    }
}

echo pais('mx', 'pais', true, false);
    
asked by Shareiv 04.12.2017 в 20:59
source

1 answer

1

To achieve what you want you must make a condition within foreach() in which you are going through the array of countries, the condition must validate that the variable $dato that receives the function is equal to $key of the country to be able to mark it as selected:

<?php 

function pais ($dato, $name, $select, $tipo){
//--    
    $my_pais = array(
        'de'        => 'Alemania',
        'mx'        => 'Mexico',
        'us'        => 'Estados Unidos',        
    );
//--    
    if ($select){
        echo "<select class=\"height_input data_input_two input__settings\" name=\"".$name."\" id=\"Language\">";
                foreach ($my_pais as $key => $my_psais) {
                    if($key == $dato){
                        echo '<option value="'.$my_psais.'" selected>'.$my_psais.'</option>';
                    }else{
                        echo '<option value="'.$my_psais.'">'.$my_psais.'</option>';
                    }
                }
        echo "</select>";
    }   
//--    
    if ($select){
        //-- 
    }else{
        return str_replace( array_keys($my_pais), array_values($my_pais), $dato);
    }
}

echo pais('de', 'pais', true, false);

?>
    
answered by 04.12.2017 / 21:04
source