How to transform a string into a select with PHP?

-1

After a SQL I have this record as a return:

// Dados
$cores = "amarelo, branco, azul, verde";

I would like to mount a select where the content of $cores is displayed as follows:

<select name="">
    <option value="amarelo">amarelo</option>
    <option value="branco">branco</option>
    <option value="azul">azul</option>
    <option value="verde">verde</option>
</select>
    
asked by anonymous 26.11.2014 / 18:01

1 answer

3

Use explode to transform the string into an array, you need to pass a delimiter that in this case is , (comma). If the value of the description is the same as value , just put the value of the variable only between <option></option> .

<?php
$cores = "amarelo, branco, azul, verde";

$arr = explode(',', $cores);

echo '<select name="cores">';
foreach($arr as $item){
    echo '<option>'. trim($item) .'</option>';
}

echo '</select>';

Example with form

    
26.11.2014 / 18:06