Give a value for input radio not selected

1

Colleagues.

I have the following code:

$array = array("A","B","C","D","E");
    for($contar = 1; $contar <= 9; $contar++){
        echo "Pergunta " . $contar . "<br>";
        foreach($array as $opcao) {
            echo $opcao . ": <input type='radio' name='respostas[".$contar."]' value='" . $opcao ."'>" . "<br>";
        }       
    }

And I'm picking up values like this:

    for($contar = 1; $contar <= 9; $contar++){  
      foreach($respostas as $resposta){
           if(!empty($resposta[$contar])){
             $valor = "1";
           }else{
             $valor = "0";
           }
       }
    }
}

I need to make the fields that are not selected receive a value of 0, but when I fill in the fields, it triples and is not in the correct order.

    
asked by anonymous 15.05.2016 / 01:02

3 answers

3

Friend I believe that if you do this way is more efficient:

foreach ($_POST["respostas"] as $value) {
    switch (trim($value)) {
        case "":
        case null:
            $valor = 0;
            break;
        default:
            $valor = 1;
    }
    echo $valor;
}

The reasons why% cos_de% is more appropriate for this, in case it will automatically check all, even if new values are added you do not need to make the modification in the code, which in this case would be necessary with the use of foreach .

The use of for also in comparison to switch in this case is more appropriate, so you can filter better and more organized.

I used if to prevent spaces at the beginning and at the end being added, an example that could come out is this: trim

    
15.05.2016 / 18:08
0

So much to do below using condition structure if of a line, to select the input radio:

<input type='radio' <?php if ($opcao == '1') echo 'checked'; ?> name='respostas[".$c."]' value='true'>" . "<br>";

Or even more simply using the thermometer operator:

<input type='radio' <?php echo $opcao == '1' ? 'checked' : ''; ?> name='respostas[".$c."]' value='true'>" . "<br>";

Note that in order to work either of the above two solutions, the variable $opcao must be of type booleana (true or false).

    
15.05.2016 / 01:10
0

Colleagues. I got it. Here is the correct answer:

for($contar = 0; $contar <= 9; $contar++){
   if($_POST["respostas"][$contar] != ""){
     $valor = "1";
   }else{
     $valor = "0";
   }
  echo $valor;
}

In this way, it sorts correctly and shows the values as per their fill. Ex.:

1
0
0
1
0
0
    
15.05.2016 / 16:37