Saving selected HTML PHP

0

I have a code of a select field where I need to be dynamically in an array the option selected by the user. Every time the user starts the page, the selected option appears. Here is the code:

       <?php    
       header("content-type: text/html; charset=utf-8");
       $cursos=array('JAVA','PHP','Python');
       ?>
      </html>
      <select value="teste">
      <option value="">Selecione</option>
      <?php
      foreach($cursos as $curso) {   
      ?>
      <option value="<?php echo $curso;?>"<?php ?>><?php echo $curso;?></option>
      <?php
      }
      ?>
     </select>
    
asked by anonymous 08.11.2014 / 20:31

3 answers

1

First you need the course variable that the user has selected.

$CURSO_DO_USUARIO === curso selecionado


<?php    
    header("content-type: text/html; charset=utf-8");
    $cursos = array('JAVA','PHP','Python');
?>
<html>
<select value="teste">
    <option>Selecione</option>
    <?php
        foreach($cursos as $curso) {
            echo "<option value='$curso'" . ($CURSO_DO_USUARIO === $curso ? " selected" : "") . ">$curso</option>";
        }
    ?>
</select>
</html>
    
08.11.2014 / 20:54
0

If I understand, I think you want this:

<?php    
       header("content-type: text/html; charset=utf-8");
       $cursos=array('JAVA','PHP','Python');
       ?>
      </html>
      <select value="teste">
      <option value="">Selecione</option>
      <?php
      foreach($cursos as $curso) {   
      ?>
<option value="<?php echo $curso; ?>"><?php echo $curso; ?></option>
     <?php }?>
 </select>

You can use this as well, by passing the index:

<select>
  <?php foreach($cursos as $key => $curso) { ?>
    <option value="<?php echo $key ?>"><?php echo $curso ?></option>
  <?php }?>
</select>
    
08.11.2014 / 20:40
0

The code looks like this:

 <?php    
 header("content-type: text/html; charset=utf-8");
 $cursos = array('JAVA','PHP','Python');
 $select_curso=$cursos;
 ?>
 <html>
 <select value="teste">
 <option>Selecione</option>
 <?php
 foreach($cursos as $curso) {
 ?>
<option value="<?php echo $curso;?>" <?php echo ($select_curso == $curso ? "  selected" : "")?>><?php echo $curso?> </option>
<?php
}
?>
</select>
</html>
    
09.11.2014 / 11:58