- PHP

How to check if is NULL in PHP

To check whether the variable is null use is_null() function.

is_null($variable)

Example:

<?php

$variable1 = 'Hello';
$variable2 = NULL;
$variable3 = 53;

var_dump(is_null($variable1)); // false
var_dump(is_null($variable2)); // true
var_dump(is_null($variable3)); // false

?>

How to check is null in if statement

<?php

if(is_null($variable)) {
  // do something if is null
} else {
  // do something if is not null
}

?>

Or if you want to perform an action only if some variable is not null, you can simply use the is_null() opposite which is !is_null. In many cases, thanks to this, you may not need an additional else.

<?php

if(!is_null($variable)) {
  // do something if the variable is not null
}

?>

Example:

<?php

$var1 = NULL;
$var2 = 'Adam';

if(is_null($var1)) {
  echo 'It is null!';
} else {
  echo $var1;
}

// Output: It is null!


if(!is_null($var2)) {
  echo 'Adam'; 
}

// Output: Adam

?>