How to turn a string into a select with PHP?

Asked

Viewed 287 times

-1

After a SQL i have how to return this record:

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

I would like to set up a select where the content of $cores 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>
  • Are you using any framework or pure PHP? You can use echos to generate HTML?

  • I’m using pure PHP !!!

  • Use a explode followed by a loop around html...

1 answer

3


Use explode to transform the string into an array, it is necessary to pass a delimiter which 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

  • 2

    I recommend blowing up just the comma, and using a trim, so in case you run away from the pattern , will still work...

  • @Kaduamaral thanks for the suggestion, I changed the answer as you spoke.

  • Can someone help me here >>> http://answall.com/questions/41972/howto return

Browser other questions tagged

You are not signed in. Login or sign up in order to post.