An Introduction to isset in PHP

Isset in PHP is an essential inbuilt PHP function that makes your PHP program more self-explanatory. However, even the PHP manual has not explained the isset function in depth. In this article, you are going to look into the isset function, as well as its various aspects in depth.

When you write a small piece of code, you can keep track of how many variables you have used or the names of the variable you have used in your code. But whenever you are dealing with a large program that contains multiple variables along with multiple arrays or array keys, there is a high possibility that you lose track of what variable names or array names are already used and names not used yet used in your code. In such cases, the isset function comes into the picture.

What is isset() in PHP?

The isset function in PHP is used to determine whether a variable is set or not. A variable is considered as a set variable if it has a value other than NULL. In other words, you can also say that the isset function is used to determine whether you have used a variable in your code or not before. It is a boolean-type function. It means that if a variable, array, or array key is not set or it has a NULL value, the isset in PHP will return false, otherwise, you will get true as the return value. You can pass multiple arguments in the isset function and it will check for all the passed parameters whether or not they are set. In this case, the isset function will return true only if all the passed arguments are set. If any of the arguments have a NULL value, the isset function will return false. 

isset() Syntax, Parameters and Return Values

Syntax of isset in PHP: 

// syntax to check if the 

// passed variables are declared

// and not equal to null or not,

// using the isset function in PHP.

isset ( mixed $var1 , mixed $var2,  ...$vars )

The parameters used in the syntax:

The parameters passed are mixed variables. This simply means that you can pass one or more variables of different data types to isset in PHP as parameters.

Return value:

The isset() returns a boolean value. It will return true if the parameter passed is declared and is not set NULL. In the case, where over one parameter is passed (they can be of different data types), the isset() will return true only if all the passed variables are not equal to NULL and their values exist. 

It will return false when a variable has not been declared or is equal to NULL. If there is more than one parameter passed, and if any of them is unset, then the returned result will be false, irrespective of the set/unset status of other variables. 

The following program illustrates the isset in PHP.

<?php

// variable of string type, 

// having empty string as its value

$var1 = '';

// variable of integer type, 

// having 1 as its value

$var2 = 1;

// variable of string type, 

$var3 = "testValue";

// variable assigned as NULL

$var4 = NULL;

// will print true, as variable exists

// and is not equal to NULL 

var_dump(isset($var1));  

var_dump(isset($var2));  

var_dump(isset($var3));  

// will print false, as variable

// is equal to NULL

var_dump(isset($var4));

// will print false, as variable does not exist

var_dump(isset($var5)); 

// will print true, as all the variables

// exist and not equal to NULL

var_dump(isset($var1, $var2, $var3));

// will print false, as var4 is equal

// to NULL

var_dump(isset($var1, $var2, $var4));  

?>

IssetInPHP_1

Full Stack Web Developer Course

To become an expert in MEAN StackView Course
Full Stack Web Developer Course

PHP Error Reporting

PHP error reporting is an important concept, especially when you are understanding the uses of isset, empty, and Null in PHP. The programs written in the PHP programming language are not converted into an executable file, instead; it directly executes them from the source code. The reason for this is that PHP is not compiled, instead, it is interpreted and is run directly. So, this can cause problems whenever there are errors in a program, as the errors which could have been detected during the compilation process, only get caught at the runtime. 

Now, there are different types of errors, they can be either trivial errors called E_NOTICE that do not cause much of a difference or harmful errors called E_ERROR that can even lead to the crash of the program. These errors in PHP are displayed in the output by default. You can also configure the php.ini file to redirect these errors to a log file, or you can disable them from being displayed to the output. You can configure and customize directives named display_errors and error_reporting available in the file named php.ini. These error reporting concepts are essential for developers to understand and apply when they are developing an application, as mishandling of errors can lead to an entire application crash.

Handling the errors of the type E_NOTICE, which are trivial, can be relatively easy. Some mistakes made by the programmers that cause E_NOTICE errors are the improper declaration and usage of variables. If a program is trying to access a non-existing variable, then it can cause an E_NOTICE type error. This can be caused by an error in logic or some typing mistake. There can also be a case where you would want to know if a variable in your program exists or not. In such cases, the isset and empty can prove to be essential. 

Unset() Function in PHP

The unset() function is another important inbuilt function provided by PHP. The unset() function is used to unset a specified variable. The functionality of the unset() function depends on the function call. If the unset() function has been called on a variable that is inside a user-defined function, then that variable will get unset locally. The scope of the unset() function will be within that function. If you use a variable with the same name as before in any other user-defined function, it will not be unset and will store the value which the user has defined. If you are willing to unset a global variable, you can use the $GLOBALS array. The unset() function returns nothing.

Syntax of unset in PHP:

// syntax to destroy variables

// by passing them to unset()

unset ( mixed $var1 , mixed $var2,  ...$vars )

The parameter in the syntax:

The parameters passed here are also mixed variables, meaning you can pass one or more variables of different data types to the unset in PHP as parameters.

Return values:

The return type of unset is void. This means that it does not return a value, instead, it completely unsets one or more of the passed variables. 

The working of the unset() varies if it is called inside a function. For instance, if you provide a variable that has been declared as global in a function, and unset() has been called on that variable inside the same function, then in such a case, it destroys the variable in its local scope only.

The following program illustrates the unset in PHP.

<?php 

    // initialize a variable

    $var1 = '1';

    echo " Value of the variable before calling unset() is: ".$var1;

    echo"";

    // calling unset to destroy the variable

    // unset

    unset($var1);

    echo " Value of the variable after calling unset() is: " .$var1;

?> 

IssetInPHP_2

Null 

NULL can not be sidelined if you are talking about the isset() function in PHP. A variable is said to be NULL if it does not contain any value. It automatically assigned these variables as NULL. You can assign the value of a variable as NULL manually or use the unset() function to assign the value NULL to a variable. 

Syntax of NULL in PHP:

// syntax to assign null 

// to a variable in PHP

$var = NULL;       

Description of the syntax:

A variable is said to be NULL if it falls into one of the following categories:

  • It assigns the constant NULL value to it.
  • It assigned no value to it.
  • unset() has been called on it.

The following program illustrates the concept of NULL in PHP.

<?php

    // assign null constant to the variable

    $myVariable = NULL;

    // this will print null

    var_dump($myVariable);

     // use $var (a null variable) to

    //  another primary variables 

   // will print 0 for integer

    var_dump( (int) $myVariable);

    // will print 0 for float

    var_dump((float)$myVariable);

    // will print false for bool 

    var_dump((bool) $myVariable) ;

    // will print false for boolean

    var_dump( (boolean) $myVariable);

?>

IssetInPHP_3.

Empty() Function

The empty() function is another vital inbuilt function provided by PHP. This function is used to check if a variable is empty or not. This function is of the boolean return type. The empty() function will return false if the variable is not empty and contains a value that is not equivalent to zero, otherwise, it will return true.

Syntax of empty() in PHP:

// syntax to to check 

// if a variable is 

// empty or not in PHP

bool empty($var);   

The parameters used in the syntax:

The empty function accepts a variable, array, or array key that you want to check whether is empty or not.

Return values

The empty function is of the boolean return type. It will return false if the variable is not empty, otherwise, it will return true.

The following program illustrates the empty function in PHP.

<?php

// initializing the variables with values

//that empty() evaluates

$a = 0;       //initialising the variable as 0 (int)

$b = 0.0;     //initialising the variable as 0 (float)

$c = "0";     //initialising the variable as 0 (string)

$d = NULL;    //initialising the variable as NULL

$e = false;

$f = array(); //initialising the variable as an empty array

$g = "";      //initialising the variable as an empty string

$h = 91;      //initializing the variable as a non zero value

// fthis will return True as a has 0 (int) value

empty($a1) ? print_r("True") : print_r("False");

// this will return True as b has 0 (float) value

empty($b2) ? print_r("True") : print_r("False");

  // this will return True as c has 0 (string) value

empty($c) ? print_r("True") : print_r("False");

  // this will return True as d has NULL value

empty($d) ? print_r("True") : print_r("False");

  // this will return True as e has been initialised as NULL

empty($e) ? print_r("True") : print_r("False");

  // this will return True as f has an empty array

empty($f) ? print_r("True") : print_r("False");

  // this will return True as g has an empty string

empty($g) ? print_r("True") : print_r("False");

 // this will return False as h has a non zero value

empty($h) ? print_r("True") : print_r("False"); 

?>

IssetInPHP_4

Function Return Values

This is an important section in accordance with the isset() and empty() functions. You already know that the isset() function and the empty() function are the language constructs i.e., they are only applicable to variables. Hence, if you try to pass a function as an argument, PHP will throw a fatal error.

isset(func1())

empty(func1())

-> Fatal error: Can't use function return value in write context

But it is not necessary to use these two functions to check if the output of the function is isset or empty. There are other ways to check the same. First of all, the function you want to check must exist. If you check for a nonexistent function, PHP will throw an error like this:

IssetInPHP_5

Such errors are very serious and can't be ignored. Now, since you already know that every function has a return type even if it returns NULL, the equivalent statements for isset and !empty functions are - 

if (func1() !== null)  -> equivalent of isset 

if (func1() == true)   -> equivalent of !empty 

if (func1())           -> concise equivalent of !empty 

if (func1() == false)  -> equivalent of empty 

if (!func1())          -> concise equivalent of empty 

Application

The prime application of the isset and empty functions is that it is used to check if a variable is set or not. These functions are appropriate to check GET and POST methods. The POST and the GET methods if not used with proper conditions can cause issues because of their less secure nature. So, you can use the isset() to make sure that input is entered in the fields, and a variable has some value so that you do not process a NULL value in your applications.

Example 1:

    // you can use the isset

    // on a submit button

    // to check if a variable

    // is set/unset.

   if(isset($_POST['submit']) 

   {

      echo("Name is: ");

      echo($_POST['name']);

   }

   // this can be used in a 

   // form in your application

 Example 2: 

   if (isset($_POST['userID'], $_POST['pass'])) {

    // input has been entered in the form

    // it will now try to log the user in

   }

    // this can be used in a sign-up or login form

Epilog 

  • Edge cases

There are some edge cases regarding the isset() function and the empty() function that you need to understand. For instance, let’s say you need to develop your application in such a way that it handles invalid URL requests. Here, you can use the isset and empty functions. After using the isset and empty functions in your application, if there is an invalid URL, then a 404 error page will also be displayed.

$currentField = fetchRecordFromDatabase($_GET['value']);

if (!$currentField) {

    errorPage(404);

}

echo $currentField;

  • Array keys

As already discussed, the isset() function can also be used to check if an array or array key is set or not. However, there is another function that is solely made for this purpose. The “array_key_exists” function serves as an alternative for “isset($array['key'])”. Just like the isset() function, this function also has a boolean data type and returns true if the array key exists, otherwise returns false. This function can detect the exact difference between a no value and NULL.

$array = array('arrayKey' => null);

// will return false

var_dump(isset($array['arrayKey']));  

 // will return true

var_dump(array_key_exists('arrayKey', $array));  

However, the isset() function alone is sufficient for such cases. While dealing with the variables, it’s the same thing for a programmer, whether a variable has no value or is set as NULL. So, you can almost achieve the same functionality with the isset () function too. But if you want to explicitly print the value of a NULL variable as ‘null’, then the array_key_exists  function will help you do the same.

Examples 

  • Difference Between NULL Character and NULL Constant

In PHP, the null character (‘\0’) and the NULL constant are not the same. When you call the isset() on a null character, it will return true, as it is different from the NULL constant.

Consider the following example to make the above point clear.

<?php

/********** isset on a variable that has been

                 assigned some value ************/

    $varWithValue = 11;

    $value1 = isset($varWithValue);    

    // this will print true, 

    // the variable is not equal to NULL

    echo var_dump(isset($value1));

    echo ""; 

/********** isset on a variable that has been

                 assigned NULL constant ************/

    $varNullConstant = NULL;

    $value2 = isset($varNullConstant);

    // this will print false, 

    // the variable is equal to NULL    

    echo var_dump(isset($varNullConstant));

    echo ""; 

/********** isset on a variable that has been

                 assigned NULL constant ************/

    $varNullCharacter = '\0';

    $value3 = isset($varNullCharacter); 

    // this will print true, 

    // the variable is equal to a null character, 

    // and not the NULL constant   

    echo var_dump(isset($value3));

    echo "";

IssetInPHP_6 

  • Use of unset()

The unset() function destroys the variable on which it is called. You can pass multiple variables of mixed data types, and it will destroy or unset all of them.

Consider the following example to see the working of the unset() in PHP.

<?php  

    // declaring test variables 

    // for testing the behavior

    // of the unset function.

    $var1 = '10';  

    $var2 = 'testString';  

    // status of the variables before unset is used.

    if (isset($var1) && isset( $var2)) {  

        echo "We are the variables having values:";

        echo $var1;

        echo $var2;

        echo "";

        var_dump (isset($var1));  

        var_dump (isset($var2));

        echo "";  

    }  

    // unset function is called

    unset ($var1);  

    unset ($var2);  

    echo "The statues of the variables after calling unset() in them:";  

    var_dump (isset($var1));  

    var_dump (isset($var2));  

?> 

IssetInPHP_7

    Stand Out From Your Peers this Appraisal Season

    Start Learning With Our FREE CoursesEnroll Now
    Stand Out From Your Peers this Appraisal Season
  • Difference Between isset and !empty

The major difference between isset and empty lies in the fact that the latter does not throw any warnings in case the variable passed to it does not exist. Whereas a warning is displayed if the isset function is used. Other than this, both of them are similar in terms of their return values and usage.

Consider the following example to understand the difference between the isset and empty in PHP.

<?php  

    // declaring a test variable

    // to check the difference in the

    // functioning of

    // isset and empty.

    $var = NULL;  

    //call isset() on var 

    echo "Here isset is called."; 

    var_dump(isset($var));

    echo ""; 

    //call empty() on var 

    echo "Here empty is called."; 

    var_dump(!empty($var));

    echo "";  

?>  

IssetInPHP_8

  • Checking Multiple Variables

The isset function in PHP can check multiple variables having different or mixed data types in one go. You can simply pass these variables as the parameters. It will return true if all of these variables exist and are not NULL. If any of them is NULL, then a false value will be returned.

Consider the following example to check multiple variables using isset in PHP. 

<?php  

    $var1 = 1;  

    $var2 = 'testString';

    $var3 = '';

    $var4 = ' '; 

    if (isset ($var1, $var2, $var3, $var4)) {  

        echo "All variables exist and they are not equal to NULL."; 

        echo ""; 

    } 

    else {  

        echo "One or more than one variable does not exist, or have a NULL value.";  

    }  

?>  

IssetInPHP_9

  • isset() to Check Session Variable

The isset function can also be used to check the values of the session variables, storing information such as the username, userID, and other data that is specific to the users on a web page.

Consider the following example to understand the working of isset in PHP with session variables.

<?php  

    // variable holding the name of the user

    $myUser = 'testUser';   

    // assign the name of the user 

    // to the session's userID

    $_SESSION['userID'] = $myUser; 

    // checking if the session variable

    // userID exists and has a non-NULL value or not.      

    if (isset($_SESSION['userID']) && !empty($_SESSION['userID'])) {  

        echo " This is an available session.";  

    } else {  

        echo "There is no session available.";  

    }  

?>  

IssetInPHP_10.

Reason to Check Both isset and empty

The !empty() function acts as the complement of the empty() function. The !empty() function is considerably equivalent to the isset() function and empty() function is equivalent to the !isset() (compliment of the isset() function) function. Both the !empty() function and the isset() function have similar functionality. Using both of the functions will result in increased time complexity and memory wastage. But there's a slight difference between both of these functions. While checking if a variable exists or not, the empty() function does not notify the programmer or give any kind of warning. 

Are you a web developer or interested in building a website? Enroll for the Full Stack Web Developer - MEAN Stack Master's Program. Explore the course preview!

Wrapping Up!

In this article, you learned about the isset function in PHP. You explored what the isset() function does and understood its syntax and parameters in depth. You saw the unset() function and empty() function along with their syntax and usage. This article also explored the difference between null character and NULL constant. It discussed the reason to check both the isset() function as well as the empty() function.

To get started with PHP, you can refer to this video.

Don’t just stop here. To learn MEAN stack development and to give yourself a chance to work for top tech giants, check out our course on Full Stack Web Developer - MEAN Stack. In this course, you will learn some of the hottest skills like Node, Mongo, etc. that will help you to set your foot into professional web development. 

If you have any questions for us, please mention them in the comments section and our experts answer them for you at the earliest.

Happy Learning!

About the Author

SimplilearnSimplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

View More
  • Disclaimer
  • PMP, PMI, PMBOK, CAPM, PgMP, PfMP, ACP, PBA, RMP, SP, and OPM3 are registered marks of the Project Management Institute, Inc.