Difference between null, empty, 0 and false
Or objective
Differentiate the day-to-day use of null
, empty
, 0
and false
.
A problem
Dealing every day with these 4 representations of variables is complicated and I don't know how to differentiate them, even more so with PHP that seems to treat them all the same.
4 answers
Scenario
I left PHP to venture into the world of C# and felt an immense difficulty to understand a little about typing. In fact, it took me a while to understand why I couldn't compare a string with null to do something if the string was empty.
After a while thinking about the problem in my head, I fell deep into the internet and ran after it. Here Comes the solution.
What is "0"?
Zero is zero and point. Who can be zero is a number, not a letter or an empty space. Zero is zero and end of conversation.
In PHP:
$n = 0;
if ($n === 0)
// true
if ($n === '0')
// false
To explain: the three adjacent equals mean exactly equal. Which in turn means content / value and type equal.
In the first conditional, we have true
as a comment because $n
is an integer/number, and its value is 0
. That is, the contents and typing are equal.
In the second conditional, the comment is false
because it compares $n
with '0'
, zero being in this case a string.
Briefly, number is a cyosa and string is another. Although they are two zeros, they are of distinct types .
What is "empty"?
When you have a variable of type string and you want to check if it has any padding, you use empty to make the comparison.
In short, it checks whether or not a string has content; whether or not it is empty.
What is null?
Null means null . You compare null when you know that a variable has a chance of possibly bringing nothing.
Want a practical example?
<?php
class Cachorro
{
public $estado;
public function sentar()
{
if ($this->estado != 'sentado')
$this->estado = 'sentado';
}
}
As we can see, I created a class Cachorro
and a method sentar
. Before the dog sits down, we check his condition. If already is sitting, it will not do anything , that is, the function not will return anything (null
); otherwise, it will change your estado
to sentado
.
To make it easier, if a trained dog wins the order to sit when he is already sitting, he will probably continue that way and will not return you anything other than the wait for a next command (null ) or perhaps a cookie for having performed a task with so much mastery.
Attention: the term null
has not only conceptual or didactic purposes. null
also specifies that a variable is not allocated in memory. For example, if we have a variable $x = 0
and then change it to $x = null
, then we did a data deallocation. In other words, we remove an information from memory.
And finally, what is "false"?
If someone asks if you are hot, most of the time there are two answer options: true
or false
. You probably won't speak 0
or will stop answering (empty
). You will say yes or no. And that's exactly what true
and false
are.
<?php
class Cachorro
{
// ...
public function latir()
{
echo 'Woof!';
return true;
}
}
In the example above, the method latir()
will return true
.
<?php
if ($cachorro->latir())
echo 'O cachorro latiu!';
else
echo 'O cachorro não latiu. :(';
And according to the above conditional, two things will be displayed:
- 'Woof!'
- ' the dog barked!';
Joining:
- 'Woof!The dog barked!';
Why does this happen?
Now in if
you are running a function and checking if her return is true. If it is, display O cachorro latiu!
. And is it true?... Of course! This is explicit in the return
method latir()
of the Class Cachorro
.
null
vs. false
, empty
e 0
Taking the previous example, but removing the return
:
<?php
class Cachorro
{
// ...
public function latir()
{
echo 'Woof!';
}
}
What type will latir()
return? Tchã tchã tchã
And the type will be.............. null !
To make a comparison of nulls in practice, follow the model:
if ($cachorro->latir() == null)
// faça algo
NULL Indicates that a variable has no value. A variable is considered NULL if it has been assigned as NULL (special value), or if a value has not yet been assigned to the variable.
Empty It is a language constructor and not a function and is used to determine if the variable is considered empty. The following values are evaluated as empty:
- "" (empty string)
- 0 (0 As Integer)
- "0" (0 how string)
- NULL
- FALSE
- array () (empty array)
- var $var; (variable declared, but no value)
About True, False or 0:
A boolean data can only contain two values: true ( true ) or false ( false).
But the big doubt arises when comparing values in PHP that because it is not a strongly typed language, does automatic conversions depending on the type of comparison :
When converting data to and from the Boolean type, several special rules apply:
A number (integer or floating point) converted to a Boolean value becomes false if the original value is zero, and true the other way around.
The string is converted to false only if it is empty or if it contains the single character '0'. If it contains anything else, even given multiple zeros, it is converted to true.
When converted to a number or a string, a Boolean value becomes 1, when true, and 0 if false.
it is important to understand that all logical operators only work with Boolean values; therefore, PHP will convert any other value to a Boolean value and then perform the operation.
PHP uses the following operators as follows:
== equivalence. Evaluates to true if the two operands are equivalent, which means that they they can be converted to a common data type that they have the same value, but are not necessarily the same data type (the above rule applies).
=== identity. Evaluates to true only if the operands are of the same data type and have the same value (the conversion rule does not apply in this case).
!= Not Equivalent Evaluates as true whether the two operands are non-equivalent, unrelated to their data type.
!= = No identical Non-identical operator. Evaluates to true if the two operands are not of the same data type or do not have the same value.
I hope I helped, the information was adapted by me from the book Zend PHP 5 Certification Study Guide and the official documentation.
I think the problem here would be differentiation of types and not' just ' values. All values asked (null
, 0
, empty
and false
) are of different types. And PHP, perhaps by convention or perhaps by simplification (or by a serious error itself,) decided to use as it uses, but why does not come to the case. Let's go to types:
Null
Or null in Portuguese, is simply the absence of a value, null
is of type null
and period. This type is extremely attached the function isset
. This function checks if the value actually exists, such as:
<?php
class Pessoa
{
public $nome = 'Fulaninho';
public function __construct($nome = null)
{
if (isset($nome)) {
$this->nome = $nome;
}
}
}
0 (zero)
As already answered, zero is zero and period. But zero is an integer (a number) other than '0'
(a string). If you have to use a function that returns a numeric value, force PHP to say that zero is a number and not a string using 'intval' or 'type casting' for (int)
. Something like:
<?php
$zero = '0';
$numero = intval($zero); // ou $numero = (int) $zero;
Empty (or empty string)
Very confused com null
, empty
it's just an empty string, something like:
<?php
$vazio = '';
if ('' === $vazio) #=> true
if (null === $vazio) #=> false
False
false
it is a boolean (as opposed to true
.)
If you ask a question to the computer:
- true
would be the answer sim
and
- false
Series não
.
Simple as that.
The big problem is that...
PHP makes a big mess with types, look:
<?php
if (0 == false) // true
if (null == false) // true
if ('' == false) // true
My advice
Here is a preference of mine, I'm sure others programmers disagree with me. I don't think there is right or wrong, just different styles of programming.
Avoid returning different types
If your function / method returns a array
of clients and, by any chance, has none, return an empty array
. If you return a string and by any chance it is empty, return empty
. And so on. Avoid null
ar everything. Avoiding things like: this function returns a string
or null
.
Or triple equal ===
is your best friend
Please use without moderation.
<?php
if (0 === false) // false
if (null === false) // false
if ('' === false) // false
// como deve ser
Follow some patterns
The PHP community together created some patterns for use and created the website PHP the right way (link in English!) to present what was created.
The empty would not be like a "space", since thus it would be an empty string. The empty is when a variable exists, but without any value defined for it.
Example:
$variavel = ""; // Ela existe, porém é vazia. Neste caso, é uma variável empty.
$variavel = " "; // Desta forma a variável não é empty, tendo um valor definido(espaço)
$variavel = null; // Neste caso, a variável deixa de existir.