163

I am told that good developers can spot/utilize the difference between Null and False and 0 and all the other good "nothing" entities.
What is the difference, specifically in PHP? Does it have something to do with ===?

2
  • It's almost impossible to actually really figure out when what is used. I guess it's important that you're CONSISTENT when you use null and when false. I prefer using null when retrieving a value from a method, because I can use isset to determine whether a value is returned instead of using empty which will not take in account: false, 0, '0' or an empty string, which can be viable values in many situations. To me it's the cleanest solution in a messy construct.
    – JMRC
    Commented Feb 11, 2016 at 18:14
  • As per @gcb comment stackoverflow.com/questions/137487/… triple equal strictly distinct one from the other where double don't. By default, use triple unless you explitely want 0 to be considered as Null or false (or the other way)
    – Harps
    Commented Nov 18, 2021 at 7:42

18 Answers 18

245

It's language specific, but in PHP :

Null means "nothing". The var has not been initialized.

False means "not true in a boolean context". Used to explicitly show you are dealing with logical issues.

0 is an int. Nothing to do with the rest above, used for mathematics.

Now, what is tricky, it's that in dynamic languages like PHP, all of them have a value in a boolean context, which (in PHP) is False.

If you test it with ==, it's testing the boolean value, so you will get equality. If you test it with ===, it will test the type, and you will get inequality.

So why are they useful ?

Well, look at the strrpos() function. It returns False if it did not find anything, but 0 if it has found something at the beginning of the string!

<?php
// pitfall :
if (strrpos("Hello World", "Hello")) { 
    // never exectuted
}

// smart move :
if (strrpos("Hello World", "Hello") !== False) {
    // that works !
}
?>

And of course, if you deal with states, you want to make a difference between the following:

  • DebugMode = False (set to off)
  • DebugMode = True (set to on)
  • DebugMode = Null (not set at all; will lead to hard debugging ;-))
12
  • 41
    Note about Null: PHP uses it as "no value" but this is not a good habit to get into. In general, Null means "unknown value" which is different than "no value" or "uninitialized variable". Nothing plus 1 is 1, while an unknown value plus one is an unknown value. Just remember that any operator applied to null will (should) result in null, because any operation on an "unknown value" results in an unknown value.
    – Eli
    Commented Oct 20, 2009 at 22:35
  • 8
    keep in mind that this is all intentions. nothing to do with what happens in reality. in reality a function can return false for non existent values (e.g. strpos, input_filter) and null for failure (e.g. input_filter). so the answer is, use ===false and/or ===null, after reading that particular function documentation.
    – gcb
    Commented Apr 18, 2011 at 9:33
  • 5
    @Eli: where do you get the idea that Null means "unknown value" in general. I can't think of any computer languages where this is true, nor does it mean that in English, at least not according to any definition I can find or have heard. Maybe you know something I don't know?
    – iconoclast
    Commented Aug 30, 2012 at 19:13
  • 2
    @iconoclast - I'm taking it from the database world. As I understand it, null is used as a placeholder for a data value that doesn't exist in the database or is unknown. See dev.mysql.com/doc/refman/5.0/en/working-with-null.html or en.wikipedia.org/wiki/Null_%28SQL%29.
    – Eli
    Commented Dec 5, 2012 at 3:39
  • 2
    Eli's not wrong. He is stating that semantically, when you use null, you signal other programmers that you don't know what's in there. It's undefined. While when you use 0, you signal that you know what's in there: an number. And here the number represent the absence of things. Remember that no matter how PHP threats values, values carry a meaning, values are a form of documentation.
    – Bite code
    Commented Jun 1, 2016 at 12:55
54

null is null. false is false. Sad but true.

there's not much consistency in PHP (though it is improving on latest releases, there's too much backward compatibility). Despite the design wishing some consistency (outlined in the selected answer here), it all get confusing when you consider method returns that use false/null in not-so-easy to reason ways.

You will often see null being used when they are already using false for something. e.g. filter_input(). They return false if the variable fails the filter, and null if the variable does not exists (does not existing means it also failed the filter?)

Methods returning false/null/string/etc interchangeably is a hack when the author care about the type of failure, for example, with filter_input() you can check for ===false or ===null if you care why the validation failed. But if you don't it might be a pitfall as one might forget to add the check for ===null if they only remembered to write the test case for ===false. And most php unit test/coverage tools will not call your attention for the missing, untested code path!

Lastly, here's some fun with type juggling. not even including arrays or objects.

var_dump( 0<0 );        #bool(false)
var_dump( 1<0 );        #bool(false)
var_dump( -1<0 );       #bool(true)
var_dump( false<0 );    #bool(false)
var_dump( null<0 );     #bool(false)
var_dump( ''<0 );       #bool(false)
var_dump( 'a'<0 );      #bool(false)
echo "\n";
var_dump( !0 );        #bool(true)
var_dump( !1 );        #bool(false)
var_dump( !-1 );       #bool(false)
var_dump( !false );    #bool(true)
var_dump( !null );     #bool(true)
var_dump( !'' );       #bool(true)
var_dump( !'a' );      #bool(false)
echo "\n";
var_dump( false == 0 );        #bool(true)
var_dump( false == 1 );        #bool(false)
var_dump( false == -1 );       #bool(false)
var_dump( false == false );    #bool(true)
var_dump( false == null );     #bool(true)
var_dump( false == '' );       #bool(true)
var_dump( false == 'a' );      #bool(false)
echo "\n";
var_dump( null == 0 );        #bool(true)
var_dump( null == 1 );        #bool(false)
var_dump( null == -1 );       #bool(false)
var_dump( null == false );    #bool(true)
var_dump( null == null );     #bool(true)
var_dump( null == '' );       #bool(true)
var_dump( null == 'a' );      #bool(false)
echo "\n";
$a=0; var_dump( empty($a) );        #bool(true)
$a=1; var_dump( empty($a) );        #bool(false)
$a=-1; var_dump( empty($a) );       #bool(false)
$a=false; var_dump( empty($a) );    #bool(true)
$a=null; var_dump( empty($a) );     #bool(true)
$a=''; var_dump( empty($a) );       #bool(true)
$a='a'; var_dump( empty($a));      # bool(false)
echo "\n"; #new block suggested by @thehpi
var_dump( null < -1 ); #bool(true)
var_dump( null < 0 ); #bool(false)
var_dump( null < 1 ); #bool(true)
var_dump( -1 > true ); #bool(false)
var_dump( 0 > true ); #bool(false)
var_dump( 1 > true ); #bool(true)
var_dump( -1 > false ); #bool(true)
var_dump( 0 > false ); #bool(false)
var_dump( 1 > true ); #bool(true)
9
  • 31
    in my opionion 0 == null is absolut nonsense, since 0 is a value and null is a flag that show the variable is uninitialized. Thanks php team
    – mercsen
    Commented Feb 18, 2013 at 8:54
  • 2
    You twice repeated your section of code starting with var_dump( null == 0 );.
    – Sparky
    Commented Mar 24, 2013 at 17:51
  • 2
    what is really weird in php : null < -1 => TRUE
    – thehpi
    Commented Sep 26, 2014 at 7:33
  • 1
    @mercsen At the least if PHP consistently behaved like 0 == null I would have been OK with it. Oddly, 0 == null and null == [], but [] != 0 !!
    – nawfal
    Commented Nov 14, 2015 at 7:31
  • 1
    strrpos('fail', 'search') will return false, and not null in my opinion is correct - if null means unknown then strrpos returning null would be like it saying 'I don't know if the string is there' rather than 'The string isn't there'.
    – Eborbob
    Commented Dec 9, 2015 at 11:52
38

Below is an example:

            Comparisons of $x with PHP functions

Expression          gettype()   empty()     is_null()   isset() boolean : if($x)
$x = "";            string      TRUE        FALSE       TRUE    FALSE
$x = null;          NULL        TRUE        TRUE        FALSE   FALSE
var $x;             NULL        TRUE        TRUE        FALSE   FALSE
$x is undefined     NULL        TRUE        TRUE        FALSE   FALSE
$x = array();       array       TRUE        FALSE       TRUE    FALSE
$x = false;         boolean     TRUE        FALSE       TRUE    FALSE
$x = true;          boolean     FALSE       FALSE       TRUE    TRUE
$x = 1;             integer     FALSE       FALSE       TRUE    TRUE
$x = 42;            integer     FALSE       FALSE       TRUE    TRUE
$x = 0;             integer     TRUE        FALSE       TRUE    FALSE
$x = -1;            integer     FALSE       FALSE       TRUE    TRUE
$x = "1";           string      FALSE       FALSE       TRUE    TRUE
$x = "0";           string      TRUE        FALSE       TRUE    FALSE
$x = "-1";          string      FALSE       FALSE       TRUE    TRUE
$x = "php";         string      FALSE       FALSE       TRUE    TRUE
$x = "true";        string      FALSE       FALSE       TRUE    TRUE
$x = "false";       string      FALSE       FALSE       TRUE    TRUE

Please see this for more reference of type comparisons in PHP. It should give you a clear understanding.

0
7

In PHP you can use === and !== operators to check not only if the values are equal but also if their types match. So for example: 0 == false is true, but 0 === false is false. The same goes for != versus !==. Also in case you compare null to the other two using the mentioned operators, expect similar results.

Now in PHP this quality of values is usually used when returning a value which sometimes can be 0 (zero), but sometimes it might be that the function failed. In such cases in PHP you return false and you have to check for these cases using the identity operator ===. For example if you are searching for a position of one string inside the other and you're using strpos(), this function will return the numeric position which can be 0 if the string is found at the very beginning, but if the string is not found at all, then strpos() will return false and you have to take this into account when dealing with the result.

If you will use the same technique in your functions, anybody familiar with the standard PHP library will understand what is going on and how to check if the returned value is what is wanted or did some error occur while processing. The same actually goes for function params, you can process them differently depending on if they are arrays or strings or what not, and this technique is used throughout PHP heavily too, so everybody will get it quite easily. So I guess that's the power.

5

False, Null, Nothing, 0, Undefined, etc., etc.

Each of these has specific meanings that correlate with actual concepts. Sometimes multiple meanings are overloaded into a single keyword or value.

In C and C++, NULL, False and 0 are overloaded to the same value. In C# they're 3 distinct concepts.

null or NULL usually indicates a lack of value, but usually doesn't specify why. 0 indicates the natural number zero and has type-equivalence to 1, 2, 3, etc. and in languages that support separate concepts of NULL should be treated only a number.

False indicates non-truth. And it used in binary values. It doesn't mean unset, nor does it mean 0. It simply indicates one of two binary values.

Nothing can indicate that the value is specifically set to be nothing which indicates the same thing as null, but with intent.

Undefined in some languages indicates that the value has yet to be set because no code has specified an actual value.

1
  • Interesting, perhaps, but does not discuss PHP at all.
    – Brad
    Commented Dec 25, 2012 at 1:39
4

I have just wasted 1/2 a day trying to get either a 0, null, false to return from strops!

Here's all I was trying to do, before I found that the logic wasn't flowing in the right direction, seeming that there was a blackhole in php coding:

Concept take a domain name hosted on a server, and make sure it's not root level, OK several different ways to do this, but I chose different due to other php functions/ constructs I have done.

Anyway here was the basis of the cosing:

if (strpos($_SERVER ['SERVER_NAME'], dirBaseNAME ()) 
{ 
    do this 
} else {
    or that
}

{
echo strpos(mydomain.co.uk, mydomain);  

if ( strpos(mydomain, xmas) == null ) 
    {
        echo "\n1 is null"; 
    }

if ( (strpos(mydomain.co.uk, mydomain)) == 0 ) 
    {
        echo "\n2 is 0"; 
    } else {
        echo "\n2 Something is WRONG"; 
    }

if ( (mydomain.co.uk, mydomain)) != 0 ) 
    {
        echo "\n3 is 0"; 
    } else {
        echo "\n3 it is not 0"; 
    }

if ( (mydomain.co.uk, mydomain)) == null ) 
    {
        echo "\n4 is null"; 
    } else {
        echo "\n4 Something is WRONG"; 
    }
}

FINALLY after reading this Topic, I found that this worked!!!

{
if ((mydomain.co.uk, mydomain)) !== false ) 
    {
        echo "\n5 is True"; 
    } else {
        echo "\n5 is False"; 
    }
}

Thanks for this article, I now understand that even though it's Christmas, it may not be Christmas as false, as its also can be a NULL day!

After wasting a day of debugging some simple code, wished I had known this before, as I would have been able to identify the problem, rather than going all over the place trying to get it to work. It didn't work, as False, NULL and 0 are not all the same as True or False or NULL?

2

From the PHP online documentation:

To explicitly convert a value to boolean, use the (bool) or (boolean) casts.
However, in most cases the cast is unncecessary, since a value will be automatically converted if an operator, function or control structure requires a boolean argument.
When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself
  • the integer ``0 (zero)
  • the float 0.0 (zero)
  • the empty string, and the string "0"
  • an array with zero elements
  • an object with zero member variables (PHP 4 only)
  • the special type NULL (including unset variables)
  • SimpleXML objects created from empty tags
    Every other value is considered TRUE (including any resource).

So, in most cases, it's the same.

On the other hand, the === and the ==are not the same thing. Regularly, you just need the "equals" operator. To clarify:

$a == $b    //Equal. TRUE if $a is equal to $b.
$a === $b   //Identical. TRUE if $a is equal to $b, and they are of the same type. 

For more information, check the "Comparison Operators" page in the PHP online docs.

Hope this helps.

1

The differences between these values always come down to detailed language-specific rules. What you learn for PHP isn't necessarily true for Python, or Perl, or C, etc. While it is valuable to learn the rules for the language(s) you're working with, relying on them too much is asking for trouble. The trouble comes when the next programmer needs to maintain your code and you've used some construct that takes advantage of some little detail of Null vs. False (for example). Your code should look correct (and conversely, wrong code should look wrong).

1

Null is used in databases to represent "no record" or "no information". So you might have a bit field that describes "does this user want to be sent e-mails by us", where True means they do, False means they don't want to be sent anything, but Null would mean that you don't know. They can come about through outer joins and suchlike.

The logical implications of Null are often different - in some languages NULL is not equal to anything, so if(a == NULL) will always be false.

So personally I'd always initialise a boolean to FALSE, and initialising one to NULL would look a bit icky (even in C where the two are both just 0... just a style thing).

1

I think bad developers find all different uses of null/0/false in there code.

For example, one of the most common mistakes developers make is to return error code in the form of data with a function.

// On error GetChar returns -1
int GetChar()

This is an example of a sugar interface. This is exsplained in the book "Debuging the software development proccess" and also in another book "writing correct code".

The problem with this, is the implication or assumptions made on the char type. On some compilers the char type can be non-signed. So even though you return a -1 the compiler can return 1 instead. These kind of compiler assumptions in C++ or C are hard to spot.

Instead, the best way is not to mix error code with your data. So the following function.

char GetChar()

now becomes

// On success return 1
// on failure return 0
bool GetChar(int &char)

This means no matter how young the developer is in your development shop, he or she will never get this wrong. Though this is not talking about redudancy or dependies in code.

So in general, swapping bool as the first class type in the language is okay and i think joel spoke about it with his recent postcast. But try not to use mix and match bools with your data in your routines and you should be perfectly fine.

1

In PHP it depends on if you are validating types:

( 
 ( false !== 0 ) && ( false !== -1 ) && ( false == 0 ) && ( false == -1 ) &&
 ( false !== null ) && ( false == null ) 
)

Technically null is 0x00 but in PHP ( null == 0x00 ) && ( null !== 0x00 ).

0 is an integer value.

1

One interesting fact about NULL in PHP: If you set a var equal to NULL, it is the same as if you had called unset() on it.

NULL essentially means a variable has no value assigned to it; false is a valid Boolean value, 0 is a valid integer value, and PHP has some fairly ugly conversions between 0, "0", "", and false.

0

Null is nothing, False is a bit, and 0 is (probably) 32 bits.

Not a PHP expert, but in some of the more modern languages those aren't interchangeable. I kind of miss having 0 and false be interchangeable, but with boolean being an actual type you can have methods and objects associated with it so that's just a tradeoff. Null is null though, the absence of anything essentially.

0

Well, I can't remember enough from my PHP days to answer the "===" part, but for most C-style languages, NULL should be used in the context of pointer values, false as a boolean, and zero as a numeric value such as an int. '\0' is the customary value for a character context. I usually also prefer to use 0.0 for floats and doubles.

So.. the quick answer is: context.

0

In pretty much all modern languages, null logically refers to pointers (or references) not having a value, or a variable that is not initialized. 0 is the integer value of zero, and false is the boolean value of, well, false. To make things complicated, in C, for example, null, 0, and false are all represented the exact same way. I don't know how it works in PHP.

Then, to complicate things more, databases have a concept of null, which means missing or not applicable, and most languages don't have a direct way to map a DBNull to their null. Until recently, for example, there was no distinction between an int being null and being zero, but that was changed with nullable ints.

Sorry to make this sound complicated. It's just that this has been a harry sticking point in languages for years, and up until recently, it hasn't had any clear resolution anywhere. People used to just kludge things together or make blank or 0 represent nulls in the database, which doesn't always work too well.

0

False and 0 are conceptually similar, i.e. they are isomorphic. 0 is the initial value for the algebra of natural numbers, and False is the initial value for the Boolean algebra.

In other words, 0 can be defined as the number which, when added to some natural number, yields that same number:

x + 0 = x

Similarly, False is a value such that a disjunction of it and any other value is that same value:

x || False = x

Null is conceptually something totally different. Depending on the language, there are different semantics for it, but none of them describe an "initial value" as False and 0 are. There is no algebra for Null. It pertains to variables, usually to denote that the variable has no specific value in the current context. In most languages, there are no operations defined on Null, and it's an error to use Null as an operand. In some languages, there is a special value called "bottom" rather than "null", which is a placeholder for the value of a computation that does not terminate.

I've written more extensively about the implications of NULL elsewhere.

1
  • 1
    offtopic, false == 0 is completely retarded. Even more so with php returning data OR failure in a function. see the return for mysql_insert_id. """The ID generated for an AUTO_INCREMENT column by the previous query on success, 0 if the previous query does not generate an AUTO_INCREMENT value, or FALSE if no MySQL connection was established.""" basically it can return A)the id, B)zero, C)false... now if that's the 1st item in the table, id will be zero! so all three values are the same! how can the developer make sense of three types of zeroes? ...and i agree with your post on null.
    – gcb
    Commented Apr 18, 2011 at 9:22
0

Somebody can explain to me why 'NULL' is not just a string in a comparison instance?

$x = 0;
var_dump($x == 'NULL');  # TRUE   !!!WTF!!!
1
  • 1
    Because PHP internally casts to the integer type and compares then. php > var_dump((int) "NULL"); // => int(0) php > var_dump((int) "BLA"); // => int(0) see php.net/manual/en/language.operators.comparison.php Translate strings and resources to numbers, usual math
    – Sevyls
    Commented Apr 29, 2019 at 13:46
-1

The issues with falsyness comes from the PHP history. The problem targets the not well defined scalar type.

'*' == true -> true (string match)
'*' === true -> false (numberic match)

(int)'*' == true -> false
(string)'*' == true -> true

PHP7 strictness is a step forward, but maybe not enough.

Not the answer you're looking for? Browse other questions tagged or ask your own question.