PHP Null

Last updated on

PHP null refers to no value that can be assigned to the PHP variable or as direct no value. On the other hand, is_null() function used to check if current value has no value or no.

The no value can be assigned to the PHP variable like in the below code example.

<?php 
   $no_value = null;
?>

Anyway, if we need to define a no value with a PHP variable, we can assign the null word like in the previous example.

However, the null PHP data type word can be used as a not case-sensitive, so it can be NULLNull, or null value.

In the next few lines, I will show you how to check if the current value of the PHP variable has no value or not. To answer this question, you have to know how to use the is_null().

Understand PHP Callback (Is Null)

The is_null() callback is a PHP predefined function, used to detect if the current variable or the returned value of another function is no value. And according to this, it will return a boolean value true or false.

According to the previous PHP example, we need to check if the $no_value variable is containing a no value or not. Let’s see that in the following PHP code.

<?php 
   
   $no_value = null;
   $is_null  = is_null( $no_value );
   
   // The Output: No Value Assigned
   if( $is_null ) {
     echo "No Value Assigned"; 
   } else {
     echo "A New Value Has Been Assigned";
   }
   
   var_dump( $is_null ); // bool(true)

?>

Anyway, according to the top PHP example, the output would be like that – “No Value Assigned”. And the output of var_dump callback will print – bool(true).

Also, there are two types else to check about the PHP null no value variables. Strict and non-strict comparison. Let’s see what is happening when we use them with the PHP null data type.

Use the PHP Null with the Strict Equality Comparison Operators

Actually, there are two types of comparison, strict equality comparison and non-strict comparison. Let’s see that.

In the following code, we will check if the $no_value has a null value or not using the comparison operators.

<?php 
   $no_value = null;
   if( $no_value === null ) {
      echo "Yes, it has no value";
   }
?>

As you saw, it is doing the same thing of the is_null() callback. But if we do the same code with the non-strict operator, it would be like the below code.

<?php 
   $no_value = null;
   $value = ( null == $no_value );
   var_dump( $value ); // bool(true)
?>

The previous code printed bool(true) because the comparison was between two values that have the same value.

Wrapping Up

The meaning of the PHP null is no value, it is used as a not case-sensitive. We can use the is_null() callback to check the current boolean value for it.

Also, the strict equality comparison operators can be used instead of the is_null() callback to get the current boolean value.

In PHP data Types tutorial, you will learn more data types in PHP.

Share on: