How to loop with input select PHP?

1

I have an array with $ c name that I made through a precise explode to do the count with for to see if it is selected. The problem is that it does the echo of option 2 or how many times there are records. Does anyone have a solution for this?

foreach($interesse_compra as $ic)
{
   $c = explode(";",$ic->cidade);
}

for($i = 0; $i < count($c);$i++)
{
   foreach($cidades as $cidade)
   {
      $select = $cidade->f_cidade == $c[$i] ?  "selected" : "";
      echo "<option value='".$cidade->f_cidade."'$select>".$cidade->f_cidade."</option>";
   }

}
    
asked by anonymous 28.07.2015 / 22:25

2 answers

3

I made a simplified version of your code, starting from the point that $c contains all cities available and that $cidades has the items to select.

A comparison is made with in_array() if current value ( $cidade ) exists in $c if possitive $select gets selected, otherwise receives an empty string.

<html>
<body>
<form>
<select multiple size="8">
<?php
    $c = ['Rio Branco', 'Maceió','Macapá','Manaus','Salvador','Fortaleza','Brasília','Vitória','Goiânia', 'Curitiba'];
    $cidades = ['São Luís','Salvador','Cuiabá','Curitiba','Campo Grande','Belém','Maceió','Belo Horizonte'];

    foreach($cidades as $cidade){
        $select = in_array($cidade, $c)  ? $select = 'selected="selected"' : "";
        printf('<option value="%s" %s>%s</option>'. PHP_EOL , $cidade, $select, $cidade);
    }
?>
</select>
</form>
</body>
</html>

Example - phpfiddle

    
29.07.2015 / 06:06
2

From the problem description, you need to check that the selected city belongs to your list of cities.

To do this, use the functions array_map () and in_array () :

$interesse = 'Recife;Campinas;Alagoas';
$cidades = ['Rio de Janeiro', 'São Paulo', 'Salvador', 'Piracicaba', 'Belo Horizonte', 'Recife'];

$interesse_array = explode(';', $interesse);

array_map(function($c) use ($cidades) {
    $selecionado = in_array($c, $cidades) ? "selected" : "false";
    echo "<option value='$c' selected='$selecionado'>$c</option>\n";
}, $interesse_array);

Output:

<option value='Recife' selected='selected'>Recife</option>
<option value='Campinas' selected='false'>Campinas</option>
<option value='Alagoas' selected='false'>Alagoas</option>

See example working on ideone .

    
28.07.2015 / 23:24