Php check if var is null

PHP is_null

Summary: in this tutorial, you’ll learn how to use the PHP is_null() construct to check if a variable is null .

Introduction to the PHP is_null() construct

PHP is_null() accepts a variable and returns true if that variable is null . Otherwise, it returns false .

is_null(mixed $v): boolCode language: PHP (php)

In this syntax, the $v is the variable to check. If $v doesn’t exist, the is_null() also returns true and issues a notice.

Since the is_null() is a language construct, not a function, you cannot call it via variable functions. For example, the following statement will result in an error:

 $f = is_null;Code language: PHP (php)

However, you can define a function that wraps the is_null() construct like this:

 function isnull($v): bool < return is_null($v); >Code language: PHP (php)

Alternatively, you can define an arrow function, assign it to a variable, and use that variable function.

 $isnull = fn($v) => is_null($v); $color = null; echo $isnull($color); // trueCode language: PHP (php)

PHP is_null() examples

The following example uses the is_null() construct and returns true because the $count variable doesn’t exist:

 var_dump(is_null($count));Code language: PHP (php)

This code also issues a notice:

Notice: Undefined variable: $countCode language: PHP (php)

The following example uses the is_null() and returns true because the $count variable is null :

 $count = null; var_dump(is_null($count)); // trueCode language: PHP (php)

The following example uses the is_null() and returns false because the $count variable is not null :

 $count = 1; var_dump(is_null($count)); // falseCode language: PHP (php)

PHP is_null() with array

The following example uses the is_null() to check if the element with the key link is null or not. It returns true because the element doesn’t exist:

 $colors = [ 'text' => 'black', 'background' => 'white' ]; var_dump(is_null($colors['link']));Code language: PHP (php)
Notice: Undefined index: linkCode language: PHP (php)

PHP is_null() with string index

The following example uses the is_null() to check if the element at index 5 in the string $message is null or not:

 $message = 'Hello'; var_dump(is_null($message[5]));Code language: PHP (php)

It returns false and issues a notice:

PHP Notice: Uninitialized string offset: 5Code language: PHP (php)

PHP is_null(), equal opeartor (==), and identity operator (===)

The echo displays an empty string for the false value, which is not intuitive. The following defines a function that displays false as the string false instead of an empty string:

 function echo_bool(string $title, bool $v): void < echo $title, "\t", $v === true ? 'true' : 'false', PHP_EOL; >Code language: PHP (php)

Comparing falsy values with null using equal operator (==)

Comparing a falsy value with null using the equal operator ( == ) will return true . For example:

The following example compares null with falsy values using the equal operator ( == ):

 function echo_bool(string $title, bool $v): void < echo $title, "\t", $v === true ? 'true' : 'false', PHP_EOL; > echo_bool('null == false:', null == false); echo_bool('null == 0:', null == 0); echo_bool('null == 0.0:', null == 0.0); echo_bool('null =="0":', null == false); echo_bool('null == "":', null == ''); echo_bool('null == []:', null == []); echo_bool('null == null:', null == null);Code language: PHP (php)
null == false: true null == 0: true null == 0.0: true null =="0": true null == "": true null == []: true null == null: trueCode language: plaintext (plaintext)

Comparing falsy value with null using identity operator (===)

The following example uses the identity operator (=== ) to compare null with falsy values, only null === null returns true .

 echo_bool('null === false:', null === false); echo_bool('null === 0:', null === 0); echo_bool('null === 0.0:', null === 0.0); echo_bool('null ==="0":', null === false); echo_bool('null === "":', null === ''); echo_bool('null === []:', null === []); echo_bool('null === null:', null === null);Code language: plaintext (plaintext)
null === false: false null === 0: false null === 0.0: false null ==="0": false null === "": false null === []: false null === null: trueCode language: PHP (php)

Comparing falsy values with null using the PHP is_null()

The following example uses the is_null() to check if falsy values are null :

 function echo_bool(string $title, bool $v): void < echo $title, "\t", $v === true ? 'true' : 'false', PHP_EOL; > echo_bool('is_null(false):', is_null(false)); echo_bool('is_null(0):', is_null(0)); echo_bool('is_null(0.0)', is_null(0.0)); echo_bool('is_null("0"):', is_null("0")); echo_bool('is_null(""):', is_null("")); echo_bool('is_null([]):', is_null([])); echo_bool('is_null(null):', is_null(null));Code language: PHP (php)
is_null(false): false is_null(0): false is_null(0.0) false is_null("0"): false is_null(""): false is_null([]): false is_null(null): trueCode language: PHP (php)

The is_null() and identity operator ( === ) return the same result.

Summary

  • The is_null() checks a value and returns true if that value is null . Otherwise, it returns false .
  • The is_null() behaves the same as the identity operator ( === ).

Источник

is_null

Finds whether the given variable is null .

Parameters

The variable being evaluated.

Return Values

Returns true if value is null , false otherwise.

Examples

Example #1 is_null() example

$foo = NULL ;
var_dump ( is_null ( $inexistent ), is_null ( $foo ));

Notice: Undefined variable: inexistent in . bool(true) bool(true)

See Also

  • The null type
  • isset() — Determine if a variable is declared and is different than null
  • is_bool() — Finds out whether a variable is a boolean
  • is_numeric() — Finds whether a variable is a number or a numeric string
  • is_float() — Finds whether the type of a variable is float
  • is_int() — Find whether the type of a variable is integer
  • is_string() — Find whether the type of a variable is string
  • is_object() — Finds whether a variable is an object
  • is_array() — Finds whether a variable is an array

User Contributed Notes 9 notes

Micro optimization isn’t worth it.

You had to do it ten million times to notice a difference, a little more than 2 seconds

$a===NULL; Took: 1.2424390316s
is_null($a); Took: 3.70693397522s

difference = 2.46449494362
difference/10,000,000 = 0.000000246449494362

The execution time difference between ===NULL and is_null is less than 250 nanoseconds. Go optimize something that matters.

See how php parses different values. $var is the variable.

strlen($var) = 0 0 1 1 1
is_null($var) = TRUE FALSE FALSE FALSE FALSE
$var == «» = TRUE TRUE TRUE FALSE FALSE
!$var = TRUE TRUE TRUE TRUE FALSE
!is_null($var) = FALSE TRUE TRUE TRUE TRUE
$var != «» = FALSE FALSE FALSE TRUE TRUE
$var = FALSE FALSE FALSE FALSE TRUE

In PHP 7 (phpng), is_null is actually marginally faster than ===, although the performance difference between the two is far smaller.

PHP 5.5.9
is_null — float(2.2381200790405)
=== — float(1.0024659633636)
=== faster by ~100ns per call

PHP 7.0.0-dev (built: May 19 2015 10:16:06)
is_null — float(1.4121870994568)
=== — float(1.4577329158783)
is_null faster by ~5ns per call

A quick test in 2022 on PHP 8.1 confirms there is still no need to micro-optimize NULL checks:

// Comparison Operator
$before = microtime ( true );
$var = null ;
for ( $i = 0 ; $i < 1000000000 ; $i ++) if( $var === null ) <>
>
$after = microtime ( true );
echo ‘ ===: ‘ . ( $after — $before ) . » seconds\n» ;

// Function
$before = microtime ( true );
$var = null ;
for ( $i = 0 ; $i < 1000000000 ; $i ++) if( is_null ( $var )) <>
>
$after = microtime ( true );
echo ‘is_null: ‘ . ( $after — $before ) . » seconds\n» ;

// ===: 4.1487579345703 seconds
// is_null: 4.1316878795624 seconds

For what I realized is that is_null($var) returns exactly the opposite of isset($var) , except that is_null($var) throws a notice if $var hasn’t been set yet.

the following will prove that:

$quirks = array( null , true , false , 0 , 1 , » , «\0» , «unset» );

foreach( $quirks as $var ) if ( $var === «unset» ) unset( $var );

echo is_null ( $var ) ? 1 : 0 ;
echo isset( $var ) ? 1 : 0 ;
echo «\n» ;
>

?>

this will print out something like:

10 // null
01 // true
01 // false
01 // 0
01 // 1
01 // »
01 // «\0»
Notice: Undefined variable: var in /srv/www/htdocs/sandbox/null/nulltest.php on line 8
10 // (unset)

For the major quirky types/values is_null($var) obviously always returns the opposite of isset($var), and the notice clearly points out the faulty line with the is_null() statement. You might want to examine the return value of those functions in detail, but since both are specified to return boolean types there should be no doubt.

A second look into the PHP specs tells that is_null() checks whether a value is null or not. So, you may pass any VALUE to it, eg. the result of a function.
isset() on the other hand is supposed to check for a VARIABLE’s existence, which makes it a language construct rather than a function. Its sole porpuse lies in that checking. Passing anything else will result in an error.

Knowing that, allows us to draw the following unlikely conclusion:

isset() as a language construct is way faster, more reliable and powerful than is_null() and should be prefered over is_null(), except for when you’re directly passing a function’s result, which is considered bad programming practice anyways.

Using === NULL instead of is_null(), is actually useful in loaded server scenarios where you have hundreds or thousands of requests per second. Saving microseconds on a lot of «simple» operations in the entire PHP execution chain usually results in being able to serve more pages per second at the same speed, or lowering your cpu usage. People usually write very bad and slow code.

$var===NULL is much faster than is_null($var) (with the same result)

I did some benchmarking with 10 million iterations:

$a=null;
isset($a); Took: 1.71841216087s
$a==NULL; Took: 1.27205181122s
$a===NULL; Took: 1.2424390316s
is_null($a); Took: 3.70693397522s
$a=5;
isset($a); Took: 1.15165400505s
$a==NULL; Took: 1.41901302338s
$a===NULL; Took: 1.21655392647s
is_null($a); Took: 3.78501200676s
error_reporting(E_ALL&~E_NOTICE);
unset($a);
isset($a); Took: 1.51441502571s
$a==NULL; Took: 16.5414860249s
$a===NULL; Took: 16.1273870468s
is_null($a); Took: 23.1918480396s

Please note, that isset is only included because it gives a good performance in any case; HOWEVER isset is NOT the same, or the opposite.
But you might be able to use isset() instead of null-checking.

You should not use is_null, except when you need a callback-function, or for conformity with is_int, is_float, etc.

I’ve found that for HTTP requests such as POST, is_null isn’t the most reliable choice for checking if empty.

if(trim($var) == «») // do something
>

I think the request does something to the input that makes it definitely not NULL.

Regarding avoidance of NULLs in your MySQL queries, why not use IS NULL and IS NOT NULL in your WHERE clauses.

SELECT *
FROM someDatabase
WHERE someAttribute IS NOT NULL

Источник

PHP: is_null() function

The is_null () function is used to test whether a variable is NULL or not.

*Mixed: Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

Return value:

Returns TRUE if var_name is null, FALSE otherwise.

Value Type: Boolean

Practice here online:

Previous: is_long
Next: is_numeric

Follow us on Facebook and Twitter for latest update.

PHP: Tips of the Day

Detecting request type in PHP (GET, POST, PUT or DELETE)

if ($_SERVER['REQUEST_METHOD'] === 'POST') < // The request is using the POST method >

For more details please see the documentation for the $_SERVER variable.

  • Weekly Trends
  • Java Basic Programming Exercises
  • SQL Subqueries
  • Adventureworks Database Exercises
  • C# Sharp Basic Exercises
  • SQL COUNT() with distinct
  • JavaScript String Exercises
  • JavaScript HTML Form Validation
  • Java Collection Exercises
  • SQL COUNT() function
  • SQL Inner Join
  • JavaScript functions Exercises
  • Python Tutorial
  • Python Array Exercises
  • SQL Cross Join
  • C# Sharp Array Exercises

We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook

Источник

Читайте также:  Site packages python mac
Оцените статью