POST Validation Doubt

0

Hey guys, I'm pretty new to php, my project was giving a:

  

notice of undefined index

So the guy showed me this code for POST validation:

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

But he did not explain how it works, can anyone explain?

    
asked by anonymous 04.08.2018 / 14:00

2 answers

4

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

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

Your code also demonstrates a ternary operation (it's 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 = '';
}
04.08.2018 / 14:11
1
  

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

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 this expression is true, and the last one returns the value if the expression is wrong. So the variable $mensagem gets the value Olá senhor .

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

    
05.08.2018 / 01:18