is_null($x) vs $x === null in PHP
There is absolutely no difference in functionality between is_null
and === null
.
The only difference is that is_null
is a function and thus
- is marginally slower (function call overhead)
- can be used as a callback, e.g.
array_map('is_null', $array)
.
Personally, I use null ===
whenever I can, as it is more consistent with false ===
and true ===
checks.
If you want, you can check the code: is_identical_function
(===
) and php_is_type
(is_null
) do the same thing for the IS_NULL
case.
The related isset()
language construct checks whether the variable actually exists before doing the null
check. So isset($undefinedVar)
will not throw a notice.
Also note that isset()
may sometimes return true
even though the value is null
- this is the case when it is used on an overloaded object, i.e. if the object defines an offsetExists
/__isset
method that returns true
even if the offset is null
(this is actually quite common, because people use array_key_exists
in offsetExists
/__isset
).
What's the difference between is_null($var) and ($var === null)?
Provided the variable is initialized (which you did indicate - though I'm not 100% sure if this matters in this context or not. Both solutions might throw a warning if the variable wasn't defined), they are functionally the same. I presume ===
would be marginally faster though as it removes the overhead of a function call.
It really depends on how you look at your condition.
===
is for a strict data comparison. NULL has only one 'value', so this works for comparing against NULL (which is a PHP constant of the null 'value')
is_null
is checking that the variable is of the NULL data type.
It's up to you which you choose, really.
What is the point of is_null()?
is_null()
Finds whether the variable is NULL
You really need isset()
which determines if a variable is set and is not NULL. Returns TRUE
if variable exists and has value other than NULL
, otherwise FALSE
.
For instance,
$something = null; then isset($something) returns false
$something = 'some value'; then isset($something) returns true
In PHP, what is the differences between NULL and setting a string to equal 2 single quotes
Null is just another datatype in PHP, which has only one value (null). Since PHP is a loosly typed language, it can be confusing how it handles different values.
"", 0, "0", False, array(), Null
are all considered False in PHP.
Null, however, is a different kind of animal. The main incompatibility with using Null is that you cannot tell if it isset().
$x = false;
isset($x) -> true
echo $x -> ""
$y = null;
isset($y) -> false
echo $y -> ""
//$z is not set
isset($z) -> false
echo $z -> E_NOTICE
So null is odd in the sense that it doesn't follow normal variable rules in PHP (at least some). In most cases, it is fine.
When it comes to database columns, PHP's NULL has no place there. You see, SQL is a string based language. SQL's NULL must be represented by NULL
with no quotes.
So if you want an EMPTY field, set it to ""
INSERT INTO foo SET bar = ""
But if you want a NULL field, set it to NULL
INSERT INTO foo SET bar = NULL
BIG DIFFERENCE.
But if you try to insert the PHP NULL directly, it will add zero characters to the query, (which leaves you with a blank or syntax error, depending on if you quoted it).
Null vs. False vs. 0 in PHP
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 found 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 DebugMode = False
(set to off), DebugMode = True
(set to on) and DebugMode = Null
(not set at all, will lead to hard debugging ;-)).
PHP check if False or Null
For returns from functions, you use neither isset
nor empty
, since those only work on variables and are simply there to test for possibly non-existing variables without triggering errors.
For function returns checking for the existence of variables is pointless, so just do:
if (!my_function()) {
// function returned a falsey value
}
To read about this in more detail, see The Definitive Guide To PHP's isset
And empty
.
How to tell whether a variable is null or undefined in php
Essentially the answer is no. There is not a single function you can create that will tell whether a runtime variable is null or is undefined. (by 'runtime variable' I mean a variable who's name you don't yet know at the time of coding. See Elaboration in the question above).
Relevant Observations:
- There's no way to retrieve the name of a variable at runtime without giving it a value and hence declaring it.
- If you pass a variable by reference, instead of by value, you're automatically declaring it. So then in the function you can't go back and determine whether it was declared before you passed it.
- You can use
array_key_exists('variable_name', $GLOBALS)
as @zzzzBov stated, to see if a variable has been declared, but only if you know the name of the variable at coding time.
Possible 'Dirty' Solutions
As @Phil (and @zzzzBov) explained you could use a messy trick of capturing error messages that would get thrown when you reference an undeclared variable.
I also considered a method where you: Make note of all the keys in
$GLOBALS
, then store a unique value in your target variable (recording it's original value first for later use). And then search$GLOBALS
looking for that unique value to determine the name of the variable AND (by comparing with your earlier look at$GLOBALS
) determine if the variable existed before. But this also seems messy and unreliable.
PHP Elvis operator vs null coalescing operator
When your first argument is null, they're basically the same except that the null coalescing won't output an E_NOTICE
when you have an undefined variable. The PHP 7.0 migration docs has this to say:
The null coalescing operator (??) has been added as syntactic sugar
for the common case of needing to use a ternary in conjunction with
isset(). It returns its first operand if it exists and is not NULL;
otherwise it returns its second operand.
Here's some example code to demonstrate this:
<?php
$a = null;
print $a ?? 'b'; // b
print "\n";
print $a ?: 'b'; // b
print "\n";
print $c ?? 'a'; // a
print "\n";
print $c ?: 'a'; // Notice: Undefined variable: c in /in/apAIb on line 14
print "\n";
$b = array('a' => null);
print $b['a'] ?? 'd'; // d
print "\n";
print $b['a'] ?: 'd'; // d
print "\n";
print $b['c'] ?? 'e'; // e
print "\n";
print $b['c'] ?: 'e'; // Notice: Undefined index: c in /in/apAIb on line 33
print "\n";
The lines that have the notice are the ones where I'm using the shorthand ternary operator as opposed to the null coalescing operator. However, even with the notice, PHP will give the same response back.
Execute the code: https://3v4l.org/McavC
Of course, this is always assuming the first argument is null
. Once it's no longer null, then you end up with differences in that the ??
operator would always return the first argument while the ?:
shorthand would only if the first argument was truthy, and that relies on how PHP would type-cast things to a boolean.
So:
$a = false ?? 'f'; // false
$b = false ?: 'g'; // 'g'
would then have $a
be equal to false
and $b
equal to 'g'
.
Check if array value isset and is null
Use array_key_exists()
instead of isset()
, because isset()
will return false
if the variable is null
, whereas array_key_exists()
just checks if the key exists in the array:
function check($array, $key)
{
if(array_key_exists($key, $array)) {
if (is_null($array[$key])) {
echo $key . ' is null';
} else {
echo $key . ' is set';
}
}
}
PHP typecasting null or int
try this:
$all_questions[] = [
'object_id' => (int) $stored_question->getObjectId(),
'question_code' => $stored_question->getQuestionCode(),
'answer' => empty($answer)? $stored_question->getAnswer(): intval($stored_question->getAnswer())
];
Related Topics
How to Refresh a Page When a Database Is Updated
Validating Us Phone Number with PHP/Regex
Algorithm for Generating a Random Number
Hide Variation Info from Cart Item Title in Woocommerce 3+
How to Pass Value from One PHP Page to Another Using Session
How to Use String Concatenation to Define a Class Const in PHP
Laravel Model Callbacks After Save, Before Save, etc
PHP Include Causes White Space at the Top of the Page
PHP String Interpolation Syntax
Pdo SQLite Could Not Find Driver... PHP File Not Processing
While ($Row = MySQL_Fetch_Array($Result)) - How Many Loops Are Being Performed
Disable Browser Cache in PHP or JavaScript in a Flash Application
PHP Function Imagettftext() and Unicode
PHP File Upload Error Tmp_Name Is Empty
PHP Files Are Downloaded by Browser Instead of Processed by Local Dev Server (Mamp)