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

3

I am trying to assign a value to a variable when the return of the search is NULL , but I am not getting it, when I check the value of the variable $IdSetor it is NULL and not zero, as necessary. >

Search 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 a picture of my query, even with the given tips I still can not do what I need, but I forgot to mention that my query generates an empty recordset, see:

    
asked by anonymous 13.03.2018 / 13:49

4 answers

3

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

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

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

}   

This else would be unnecessary. To give oneself value itself is redundancy. But you can use else for another action if the value is not null .

    
13.03.2018 / 13:55
4

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

$IdSetor = ($IdSetor === null) ? 0 : $IdSetor;
    
13.03.2018 / 14:12
3

A little leaner, with no redundancy:

if (is_null($IdSetor)) $IdSetor = 0;
    
13.03.2018 / 14:16
2

From PHP 7, there is the null coalescer 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), it will become zero.

See working at Ideone | Repl.it

Or, to make it even more readable, do it straight:

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

What eliminates the need to perform the subsequent verification.

Null coalescence operator

    
13.03.2018 / 14:11