Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
PHP NULL
In PHP, a variable with no value is said to be of null data type. Such a variable has a value defined as NULL. A variable can be explicitly assigned NULL or its value can be set to null by using the unset() function.
Syntax
$var = NULL;
It is possible to cast a variable of other type to null, although casting null to other type has been deprecated from PHP 7.2. In earlier versions, casting was done using (unset)$var syntax.
Example
Following example shows how to assign NULL to a variable ?
<?php $var = NULL; var_dump($var); ?>
NULL
Type Casting from NULL
The following example demonstrates casting a null variable to other primary data types ?
<?php $var = NULL; var_dump((int) $var); var_dump((float) $var); var_dump((bool) $var); var_dump((string) $var); ?>
int(0) float(0) bool(false) string(0) ""
Using unset() Function
You can also create NULL values using the unset() function ?
<?php $name = "John"; echo "Before unset: "; var_dump($name); unset($name); echo "After unset: "; var_dump($name); ?>
Before unset: string(4) "John" After unset: NULL
Checking for NULL Values
Use is_null() function to check if a variable is NULL ?
<?php $var1 = NULL; $var2 = ""; $var3 = 0; var_dump(is_null($var1)); // true var_dump(is_null($var2)); // false var_dump(is_null($var3)); // false ?>
bool(true) bool(false) bool(false)
Conclusion
NULL represents the absence of a value in PHP. It can be assigned directly, created with unset(), and checked using is_null(). When cast to other types, NULL converts to empty or false values.
