How to capture value from select as string in PHP?

1

I'm doing a form in PHP, when it captures the data from a select it returns me only as 0 or 1, I would like it to show what the person selected:

<select class="form-control" name="pergunta1" required>
                                    <option selected="" value="">ESCOLHA SUA RESPOSTA</option>
                                    <option value="camuflado">CAMUFLADO</option>
                                    <option value="gancho">GANCHO</option>
                                    <option value="estimulante">ESTIMULANTE</option>
                                    <option value="lamina">LÂMINA SÔNICA</option>
                                    <option value="holopiloto">HOLOPILOTO</option>
                                    <option value="escudo">ESCUDO</option>
                                    <option value="cronossalto">CRONOSSALTO</option>
                                </select> 


<?php 
$resposta1 = isset($_GET['pergunta1'])?isset($_GET['pergunta1']):0;
$resposta2 = isset($_GET['pergunta2'])?isset($_GET['pergunta2']):0; 

echo "$resposta1";
?>

When it returns the echo it returns as 1 or 0, would like it to return as a string, for example if the person selected "camouflaged" returns "camouflaged" instead of 1 or 0.

    
asked by anonymous 23.01.2018 / 18:20

1 answer

3

You are double-checking whether the variable sent to the GET is set. In this case, just use:

$resposta1 = isset($_GET['pergunta1'])?$_GET['pergunta1']:0;

In the above example, we check whether the variable $_GET['pergunta1'] , through the function isset() , is set if we do not assign the value 0 to $_GET['pergunta1'] .

Reference: Article .

References: isset () , structure if .

EDIT:

There is also a new comparison operator called Null Coalescence. Implemented from version 7.0 of PHP.

It basically replaces the isset () function. For example:

Your current line of code is this:

 $resposta1 = isset($_GET['pergunta1'])?$_GET['pergunta1']:0;

With the Coalescence Operator Null it would look like this:

$resposta1 = $_GET['pergunta1'] ?? 0;

You'll get the same result, and this will help save time and line in your codes.

    
23.01.2018 / 18:40