Saving Selected HTML PHP

Asked

Viewed 136 times

0

I have a code from a select field and I need it to be dynamically in an array the option selected by the user. Every time the user starts the page the selected option appears. Follows 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>

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>
  • This $CURSO_DO_USUARIO variable has to receive the array if selected, Selected will appear on the screen of the selected option.

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 as well by passing the index:

<select>
  <?php foreach($cursos as $key => $curso) { ?>
    <option value="<?php echo $key ?>"><?php echo $curso ?></option>
  <?php }?>
</select>
  • I need Selected to receive the array.

  • Okay, I’ll edit it! So your code there is not working ?

  • Try so doing favor

0

The code went 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>

Browser other questions tagged

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