Difference between null, Empty, 0 and false

Asked

Viewed 20,996 times

13

The goal

Differentiate the day-to-day use of null, empty, 0 and false.

The 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.

  • 2

    William, would you please edit the question so that it sounds like a question, and not as an introduction to the answer? I believe it will work better on our platform. Ah, and it’s totally valid to ask and answer your own question; you don’t need to mark the answer as wiki, it’s fair to earn points for it.

  • 1

    @bfavaretto Ready, my dear. Thanks for the tips!

  • We could consider Empty to be a space?

  • A good tip (as always) is the official documentation. This Appendix of the documentation shows how the different variable test functions work on different values with different types. http://www.php.net/manual/en/types.comparisons.php

4 answers

14


Setting

I left PHP to venture into the world of C# and felt an immense difficulty to understand a little bit about typography. In fact, it took me a while to understand why I couldn’t compare string with null to do something if the string was empty.

After a while pondering the problem in the head, I fell deep into the internet and ran after. Lo and behold the solution comes next.


What is "0"?

Zero is zero and dot. Who can be zero is a number, not a letter or an empty space. Zero is zero and end of chat.

In PHP:

$n = 0;

if ($n === 0)
    // true

if ($n === '0')
    // false

To explain: the three adjacent equations mean exactly the same. Which, in turn, means content/value and guy equal.

On first parole, we have true as a comment because $n is an integer/number, and its value is 0. That is, the content And typing is the same.

On the second parole, the comment is false because he compares $n with '0', zero being, in this case, a string.

Briefly, number is a jealous and string is another. Although they are two zeros, they are distinct types.

What is the "Empty"?

When you have a variable of type string and want to check if they have any fillers, you use the Empty to make the comparison.

In short, it checks whether a string has content; whether or not it is empty.

What is the "null"?

null means null. You compare null when you know that a variable has the chance to possibly not bring anything.

They 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, we check his condition. If he is already seated, he will do nothing, that is to say, the function nay will return nothing (null); otherwise it will alter your estado for sentado.

To make it easier, if a trained dog wins the order to sit down when he is already seated, he will probably continue that way and will not return anything to you beyond waiting for a next command (null) or perhaps a cookie for having performed such a masterful task.

Heed: the term null does not have 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 we moved on to $x = null, then we made a data offset. In other words, we removed information from memory.

And finally, what is "false"?

If someone asks you if you are hot most of the time, there are two answer options: true or false. You probably won’t talk 0 or you’ll stop answering (empty). You will say yes or nay. And that’s exactly what the true and false sane.

<?php

class Cachorro
{
    // ...

    public function latir()
    {
        echo 'Woof!';
        return true;
    }
}

In the above example, 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 parole, two things will be displayed:

  1. 'Woof!'
  2. 'The dog barked!';

Joining together:

  1. 'Woof! The dog barked!';

Why does this happen?

Now, in the 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 it is! This is explicit in return of the method latir() class Cachorro.

null vs. false, empty and 0

Taking the previous example, but removing the return:

<?php

class Cachorro
{
    // ...

    public function latir()
    {
        echo 'Woof!';
    }
}

What kind will be latir() will return? Bye bye bye bye bye

And the guy will be.............. null!

To make a comparison of nulls in practice, follow the model:

if ($cachorro->latir() == null)
    // faça algo

3

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 whether the variable is considered empty. The following values are evaluated as Empty (empty):

  • "" (empty string)
  • 0 (0 as whole)
  • "0" (0 as string)
  • NULL
  • FALSE
  • array() (empty array)
  • var $var; (declared variable, 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 for not being 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 opposite.

The string is converted to false only if it is empty or if it contains the unique character '0'. If it contains anything else, even multiple zeros data, 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 as true if the two operands are equivalent, meaning that 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 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).

!= Non-equivalent Evaluates to true if the two operands are non-equivalent, unrelated to their data type.

!== Non-identical Non-identical operator. Evaluates to true whether the two operands are not of the same data type or do not have the same value.

I hope to have helped, the information was adapted by me from the book Zend PHP 5 Certification Study Guide and the official documentation.

2

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 even by a major error,) decided to use as it uses, but why is not the case. Let’s go to the guys:

null

Or null in Portuguese, is simply the absence of value, null is the type null point. This type is extremely connected to function isset. This function checks if the value actually exists, for example:

<?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 dot. But zero is an integer (a number) other than '0' (a string). If Voce has to use a function that returns a numerical value, force PHP to say that 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 with null, empty is just an empty string, something like:

<?php

$vazio = '';

if ('' === $vazio) #=> true
if (null === $vazio) #=> false

false

false is a boolean (unlike true.)

If Voce asks the computer a question: - true would be the answer sim and - false would be não.

Simple as that.

The big problem is that...

PHP makes a big mess with the guys, check it out:

<?php

if (0 == false) // true
if (null == false) // true
if ('' == false) // true

My advice

Here is a preference of mine, I’m sure that other programmers disagree with me. I think there is no right or wrong, just different styles of programming.

Avoid returning different types

If your function/method returns a array of customers and, by some chance, have none, return a array empty. If you return a string and by any chance it is empty, return empty. And so on. Avoid nullair everything. Avoiding things like: this function returns a string or null.

The same triple === 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 site PHP the right way (link in English! ) to present what has been created.

0

The Empty it would not be like a "space", because then it would be an empty string. The Empty is when a variable exists, but with no defined value 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.

Browser other questions tagged

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