How to distinguish FALSE from empty string?

6

Several PHP functions (eg SplFileObject :: fgets ) return FALSE in case of error (eg end of file), but may also return an empty string (in this example, if the file has an empty line); it is impossible to distinguish the two cases with the naive test

$line = $file->fgets();
if ($line) { /* errado! */ }

What is the least wordy way to detect an error in a function call?

    
asked by anonymous 16.06.2015 / 22:50

1 answer

8

Use the triple operator !== or === :

if ($line !== FALSE) { /* Correto */ }

The double operators == and != compares only the value itself, whereas the triple operators !== and === also compares the data type.

Examples of use:

// String
""     ==  FALSE -> Verdadeiro
""     === FALSE -> Falso
"algo" ==  TRUE  -> Verdadeiro
"algo" === TRUE  -> Falso

""     !=  FALSE -> Falso
""     !== FALSE -> Verdadeiro
"algo" !=  TRUE  -> Falso
"algo" !== TRUE  -> Verdadeiro

// Array
[]     ==  FALSE -> Verdadeiro
[]     === FALSE -> Falso 
['oi'] ==  TRUE  -> Verdadeiro
['oi'] === TRUE  -> Falso 

[]     !=  FALSE -> Falso
[]     !== FALSE -> Verdadeiro 
['oi'] !=  TRUE  -> Falso
['oi'] !== TRUE  -> Verdadeiro 

// Número
0 ==  FALSE -> Verdadeiro
0 === FALSE -> Falso
1 ==  TRUE  -> Verdadeiro
1 === TRUE  -> Falso

0 !=  FALSE -> Falso
0 !== FALSE -> Verdadeiro
1 !=  TRUE  -> Falso
1 !== TRUE  -> Verdadeiro

//Tipagens diferente
'0' == 0    -> Verdadeiro
'0' === 0   -> Falso
'1' == 1    -> Verdadeiro
'1' === 1   -> Falso

'0' != 0    -> Falso
'0' !== 0   -> Verdadeiro
'1' != 1    -> Falso
'1' !== 1   -> Verdadeiro

Warning: The use of if and while without logical operation, ie:

if ($line)
while($line)

It's the same as using the double operator == :

if ($line == TRUE)
while($line == true)

Attention²:

Some functions return true values but are interpreted as false by the simple operator, such as the strpos() , for example:

if (strpos('algo', 'a')) -> Falso (Aqui o retorno é 0, e este valor é interpretado como false pelo operador simples)
if (strpos('algo', 'a') !== FALSE) -> Verdadeiro

Described in function documentation strpos() :

  

Warning   This function may return the FALSE boolean, but may also return a non-Boolean value that can be evaluated as FALSE , such as 0 or "" . Read the Boolean section for more information. Use the === operator to test the value returned by this function.

For more information on PHP operators, see Online Documentation .

    
16.06.2015 / 22:55