How to distinguish FALSE from empty string?

Asked

Viewed 347 times

6

Various PHP functions (e. g. Splfileobject::fgets) return FALSE in case of error (e.g. end of file), but can 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 prolix way to detect an error in a function call like this?

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

Heed: The use of if and of while without logical operation, i.e.:

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, as is the case of the function 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 job documentation strpos():

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

For more information about PHP operators see Documentation Online.

  • It makes a difference to write FALSE or false?

  • Opa @ctgPi, no no. I like it like this, but you can write it the way you think best... ;)

Browser other questions tagged

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