Doubt about validation of POST

Asked

Viewed 97 times

1

Hi guys, I’m quite beginner in php, my project was giving a:

notice de Undefined index

Then the guy showed me this code for the validation of the POST:

$texto = isset($_POST['texto']) ? $_POST['texto'] : ''; 

But he didn’t explain to me how it works?

  • Put the code and the error that came up, so it is easier to help you

  • Actually I only wanted the explanation of this code: $text = isset($_POST['text']) ? $_POST['text'] : '';

2 answers

4


First you need to understand what the error of undefined. This error indicates that there is no value in your variable, thus the function isset checks whether the variable is defined or not.

$texto = isset($_POST['texto']) ? $_POST['texto'] : ''; 

Your code also demonstrates a ternary operation (it is a if/else in the short version let’s say so)

$texto = condição ? TextoDefinido : TextoNaoDefinido;

Version if/else:

if(isset($_POST['texto'])){
    $texto = $_POST['texto'];
}else{
    $texto = '';
}
  • Thank you very much, man, now I get it :D

2

The ternary operator is a version of IF…ELSE, which consists of grouping, on the same line, the commands of the condition.

traditional condition IF…ELSE:

$sexo = 'M';

if($sexo == 'M'){
    $mensagem = 'Olá senhor';
}else{
    $mensagem = 'Olá senhora';    
}

condition with ternary operator:

$sexo = 'M';
$mensagem = $sexo == 'M' ? 'Olá senhor' : 'Olá senhora' ;

The first parameter receives an expression, the second is the return if that expression is true, and the latter returns the value if the expression is wrong. Thus the variable $mensagem gets the value Olá senhor.

About, notice de undefined is a simple warning that the variable has not been initialized, ie the variable does not yet have a definition.

Browser other questions tagged

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