Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning NULL to a variable in PHP: what does that do?

Tags:

php

null

In maintaining code, I'm encountering loops, where at the end of the loop several variables are set to NULL like so: $var = NULL;. From what I understand in the manual, NULL is meant mostly as something to compare against in PHP code. Since NULL has no type and is not a string or number, outputting it makes no sense.

I unfortunately cannot provide an example, but I think the NULL values are being written to a file in our code. My question is: does $var have a value after the assignment, and will echoing/writing it produce output?

EDIT: I have read the PHP manual entry on NULL. There is no need to post this: http://php.net/manual/en/language.types.null.php in a comment or answer, or top downvote me for not having RTM. Thank you!

like image 627
toon81 Avatar asked Jun 22 '12 14:06

toon81


People also ask

What does setting a variable to null do?

The set <variable> to null construct sets a project variable to no value. <variable> refers to the variable of bound entity that is referenced in the agent descriptor file.

What is the use of null in PHP?

PHP NULL Value Null is a special data type which can have only one value: NULL. A variable of data type NULL is a variable that has no value assigned to it.

Is null the same as empty in PHP?

This simply means that all NULL data type values in PHP are considered empty , but not all empty variables are NULL . In the example above, $var1 is of data type integer.

Does null return false PHP?

A variable is considered to be NULL if it does not store any value. It returns TRUE if value of variable $var is NULL, otherwise, returns FALSE. Example: PHP.


2 Answers

Null in PHP means a variable were no value was assigned.

http://php.net/manual/en/language.types.null.php

like image 55
Arno 2501 Avatar answered Nov 15 '22 19:11

Arno 2501


null is pretty much just like any other value in PHP (actually, it's also a different data type than string, int, etc.).

However, there is one important difference: isset($var) checks for the var to exist and have a non-null value.

If you plan to read the variable ever again before assigning a new value, unset() is the wrong way to do but assigning null is perfectly fine:

php > $a = null;
php > if($a) echo 'x';
php > unset($a);
php > if($a) echo 'x';
Notice: Undefined variable: a in php shell code on line 1
php >

As you can see, unset() actually deletes the variable, just like it never existed, while assigning null sets it to a specific value (and creates the variable if necessary).

A useful use-case of null is in default arguments when you want to know if it was provided or not and empty strings, zero, etc. are valid, too:

function foo($bar = null) {
    if($bar === null) { ... }
}
like image 34
ThiefMaster Avatar answered Nov 15 '22 17:11

ThiefMaster