Use isset() and empty() effectively to check data in PHP

isset() function

The isset() function is a built-in function in PHP that checks if a variable is set and that the variable is not NULL. This function also checks if the declared variable, array, or array key has a null value, and if it exists, isset() returns false, and true in all other possible cases.

The syntax is as follows:

bool isset( $var, mixed )

Parameters: This function accepts multiple parameters. The first argument to the function is $var. This parameter is used to store the value of the variable.

Example:

<?php
  
//PHP program to illustrate 
//isset() function
$num = '0' ;
  
if ( isset( $num ) ) {
     print_r( " $num is set with isset function <br>" );
}
  
//Declare an empty array 
$array = array (); 
    
//Use isset function 
echo isset( $array [ 'geeks' ]) ? 
'array is set.' :  'array is not set.' ; 
?>

The output is as follows:

0 is set with isset function array is not set.

empty() function

The empty() function is a language construct used to determine whether a given variable is null or NULL. The empty() function is the negation or complement of the empty() function. empty() function with ! isset() function, and ! The empty() function is equal to the isset() function.

Example:

<?php
  
//PHP program to illustrate
//empty() function
  
$temp = 0;
  
//It returns true because 
//$temp is empty
if ( empty ( $temp )) {
     echo $temp . ' is considered empty' ;
}
  
echo "\n" ;
  
//It returns true since $new exist
$new = 1;
if (! empty ( $new )) {
     echo $new . ' is considered set' ;
}
?>

The output is as follows:

0 is considered empty
1 is considered set

Reasons to check both features at the same time:

isset() and ! The empty() function is similar, and both will return the same result. But the only difference! The empty() function does not generate any warnings or electronic notifications when the variable does not exist. It is enough to use any one of these features. By merging two functions into a program, it will result in the passage of time and unnecessary memory usage.

Example:

<?php
  
//PHP function to demonstrate isset()
//and !empty() function
  
//Inintialize a variable
$num = '0' ;
  
//Check isset() function
if ( isset ( $num ) ) {
     print_r( $num . " is set with isset function" );
}
  
//Display new line
echo "\n" ;
  
//Inintialize a variable
$num = 1;
  
//Check the !empty() function
if ( ! empty ( $num ) ) {
     print_r( $num . " is set with !empty function" );
}

The output is as follows:

0 is set with isset function
1 is set with !empty function