Assign a value to a variable when the search return is NULL

Asked

Viewed 132 times

3

I’m trying to assign a value to a variable when the search return is NULL, but I’m not getting it, when I check the value of the variable $IdSetor she is NULL and not zero, as I need.

The research and what I’m trying to do:

// BUSCANDO IdSetor
$sqlVerSetor = "SELECT IdSetor FROM cadSetor WHERE IdSetorOld = ?";
$stm = $conexao->prepare($sqlVerSetor);
// DEFINE O TIPO DA VARIÁVEL INT OU STR
$stm->bindValue(1, $LotacaoRH, PDO::PARAM_INT);      
$stm->execute();    
$ResDadosSetor = $stm->fetchAll(PDO::FETCH_OBJ); 
// CONTAGEM DE REGISTROS RETORNADOS
$conSqlRegSetor = count($ResDadosSetor);            
// FECHANDO A CONSULTA
$stm->closeCursor(); 

foreach($ResDadosSetor as $RegSetor) {  

    $IdSetor = $RegSetor->IdSetor;                  

    if ($IdSetor == NULL) {
        $IdSetor = 0;
    } else {
        $IdSetor = $IdSetor;
    }   
}

I will put an image of my query, even with the tips given I still could not do what I need, but forgot to mention that my query generates an empty set of records, see:

inserir a descrição da imagem aqui

4 answers

4

Another option is to use the identical operator === when comparing the values.

$IdSetor = ($IdSetor === null) ? 0 : $IdSetor;

3


Use the function is_null(), returning true if the variable is null:

if (is_null($IdSetor)) {
   $IdSetor = 0;
} else {

    // O valor não é null
    // fazer algo aqui

}   

That one else would be unnecessary. Assigning yourself the value itself is redundancy. But you can use the else for another action if the value is not null.

  • 1

    That one else is it really necessary? hehe

  • rsrs... had not even noticed

  • @dvd, if the return is not null need to burn the returned value.

  • @adventistapr Vc would not want to assign 0 to $Idsetor if it were null?

  • @adventistapr I updated the answer. See if this is what I wanted.

  • That’s right @dvd, I appreciate the help.

Show 1 more comment

3

A little more lean, no redundancy:

if (is_null($IdSetor)) $IdSetor = 0;

2

Starting with PHP 7, there is the null coalescence operator, which returns the first operand if it exists and is not null, otherwise returns the second operand. In this case, just do:

$IdSetor = $IdSetor ?? 0;

If $IdSetor is null (or does not exist), will become zero.

See working on Ideone | Repl.it

Or, to make it even more readable, make it direct:

$IdSetor = $RegSetor->IdSetor ?? 0;

This eliminates the need for further verification.

Operator of null coalescence

  • That tip was really good.

Browser other questions tagged

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