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.
Reported: String comparison
– Guilherme Nascimento