Difference between null, empty, 0 and false

11

The goal

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

The problem

Coping with these 4 representations of variables is complicated and I do not know how to differentiate them, even more so with PHP that seems to treat them all the same.

    
asked by anonymous 29.01.2014 / 13:53

4 answers

13

Scenario

I left PHP to venture into the C # world and felt a tremendous difficulty to understand a bit about typing. In fact, it took me a while to understand why I could not compare a string with null to do something if the string was empty .

After a while of the problem in the head, I fell into the background on the internet and ran after. Here is the solution that follows.

What is "0"?

Zero is zero and period. 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 equalities mean exactly the same . That in turn means content / value and type .

In the first conditional, we have true as comment because $n is an integer / number, and its value is 0 . That is, the content E typing are the same.

In the second conditional, the comment is false because it compares $n with '0' , where zero is a string in this case.

In short, number is a ciosa 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 it has any fill, you use empty to do 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 compute null when you know that a variable has the 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 you can see, I created a Cachorro class and a sentar method. Before the dog sat down, we checked his condition. If you're already seated, it will not do anything , that is, the no function will return nothing ( null ) ; otherwise, it will change its estado to 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 you anything other than waiting for a next command ( null ) or perhaps a cookie for having performed a task so masterfully.

Attention: The term null is not just for conceptual or didactic purposes. null also specifies that a variable is not allocated in memory. For example, if we have a $x = 0 variable and then change to $x = null , then we have done a deallocation of data. In other words, we removed an information from memory.

And finally, what is "false"?

If someone asks you if you are hot, most of the time, there are two options for answer: true or false . You probably will not talk 0 or will stop responding ( empty ). You will say yes or no . And that's just what true and false are.

<?php

class Cachorro
{
    // ...

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

In the example above, the latir() method will return true .

<?php

if ($cachorro->latir())
    echo 'O cachorro latiu!';
else
    echo 'O cachorro não latiu. :(';

And according to the conditional above, two things will be displayed:

  
  • 'Woof!'
  •   
  • 'The dog barked!';
  •   

    Putting together:

      
  • 'Woof! The dog barked!';
  •   

    Why does this happen?

    Now in if you are executing a function and checking if returns true . If it is, display O cachorro latiu! . And is it true? ... Of course! This is explicit in return of method latir() of class Cachorro .

    null vs. false , empty and 0

    Taking the previous example, but removing return :

    <?php
    
    class Cachorro
    {
        // ...
    
        public function latir()
        {
            echo 'Woof!';
        }
    }
    

    What kind of latir() will return? Tchã 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
    
        
    29.01.2014 / 14:06
    2

    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 variable value has not yet been assigned.

    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 an integer)
    • "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 .

    But the big question arises when comparing values in PHP that are 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 otherwise.

    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 several zeros data, it is converted to true.

    When converted to a number or a string, a Boolean value becomes 1, when true, and 0 is false.

    It is important to understand that all logical operators only work with Boolean values; so PHP will convert any other value to a Boolean value and then perform the operation.

    PHP uses the following operators as follows:

    == Equivalence. It evaluates to true if the two operands are equivalent, which means 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 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 to true if the two operands are non-equivalent, unrelated to their data type.

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

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

        
    29.01.2014 / 16:13
    1

    I think the problem here would be the differentiation of types rather than 'just' of values. All the requested values ( null , 0 , empty and false ) are of different types. And PHP, perhaps by convention or perhaps by simplification (or by a gross error,) has decided to use it as it uses, but why is not the case. Let's go to the types:

    null

    Or null in Portuguese, it is simply the absence of value, null is of type null and period. This type is extremely connected to isset function. This function checks whether 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 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)

    Too 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 (the opposite of true .)

    If you ask the computer a question:  - true would be the answer sim e  - false would não .

    Simple like this.

    The big problem is that ...

    PHP makes a big mess with the types, look:

    <?php
    
    if (0 == false) // true
    if (null == false) // true
    if ('' == false) // true
    

    My advice

    Here is my preference, I'm sure other programmers will disagree with me. I think there is no right or wrong, just different styles to program.

    Avoid returning different types

    If your function / method returns a array of clients and, by any chance, does not have any, return an empty array . If a string is returned and by chance is empty, return empty . And so on. Avoid% with all air. Avoiding things like: this function returns a null or string .

    Triple equal equal null 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 to use and created the PHP the right way to submit what was created.

        
    29.01.2014 / 19:15
    0

    empty would not be like a "space", so it would be an empty string. empty is when a variable exists, but with no 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.
    
        
    29.01.2014 / 16:45