How to capture select value as a string in PHP?

Asked

Viewed 526 times

1

I am making a form in PHP, when it captures the data of a select it returns me only as 0 or 1, I would like it to show what the selected person:

<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 echo it returns as 1 or 0, I would like it to return as string, for example if the person selected "camouflaged" q returns "camouflaged" instead of 1 or 0.

  • 1

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

  • mmmuuuuuiittooooo thanks, I’m too new still, I’m catching a lot. ma vlww

  • You’re welcome, good luck

  • and if I need to compare this value with if Else?? for example: <? php $resposta1 = isset($_GET['question1'])?($_GET['question1']): 0; $resposta2 = isset($_GET['Pergunta2'])?($_GET['Pergunta2']): 0; if($answer1 = HOW TO PLACE HERE VALUE "CAMOUFLAGED"?){ echo "camouflaged"; } Else;?>

  • leaves, I got here rsrsr

1 answer

3


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

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

In the acimá example we verify if the variable $_GET['pergunta1'], through function isset(), is defined if we do not assign the value 0 to $_GET['pergunta1'].

Reference: Article.

References: isset(), if structure.


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 Null Coalescence Operator would be as follows:

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

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

Browser other questions tagged

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