I do not know how to handle a "no selection" in a select

0

I have a select like this:

<select multiple name="claseUsuario[]">
   <option value="1">Tipo 1</option>
   <option value="2">Tipo 2</option>
   <option value="3">Tipo 3</option>
   <option value="4">Tipo 4</option>                    
</select>

then by PHP I transfer it like this:

$usuclase = $_POST['claseUsuario'];

if (isset($usuclase)) {
    foreach($usuclase as $claseUsuario){
      echo $claseUsuario;
    }
} else {
    $usuclase = '0';
}

The user can not select anything, which would give me the option to be another type of user, let's say the user "0"...

Now, something is wrong because with the echo that of foreach I can see each value when you select something in select but when you do not select anything it throws me this error:

  

"Undefined index: userClass"

What can be happening?

equal replacing with:

if (isset($_POST['claseUsuario'])) {

  foreach($usuclase as $claseUsuario){
    echo $claseUsuario;
  }
} else {
  $usuclase = ['0'];
}

neither walks ...

    
asked by MNibor 08.06.2017 в 21:22
source

1 answer

0

No, you are using an undefined variable before checking if it is defined, your code should look like this:

if (isset( $_POST['claseUsuario'])) {  //¿Existe este post?
   $usuclase = $_POST['claseUsuario']; //Usamos la variable dentro de POST

   foreach($usuclase as $claseUsuario){ //podemos iterar seguramente porque SI existe
      echo $claseUsuario;
    }

} else {
    $usuclase = '0'; 
}
    
answered by 09.06.2017 в 05:39