Check if a variable in PHP does exist or not

In PHP, we often see the “Undefined variable” notice. The notice shows when the variable we call does not exist.

In this post, we are going to see how to check if a variable in PHP exists or not. In this way, we will be able to avoid theĀ “Undefined variable” notice. We are going to check the existence of the variable before we call it.

To check if a particular variable does exist or, we are going to use PHP isset(). It will return TRUE if the variable exists and return FALSE if it does not exist. Below is the syntax:

isset(VARIABLE_NAME)

Now let’s see the example below:

<?php

$var = "Some value";
if (isset($var)) {
  echo $var;
} else {
  echo "Variable does not exist";
}

?>

In the above example, we have taken a variable. Using the PHP isset() we have first checked if the variable exists or not. If it returns TRUE or the variable exists it will show the variable value on the web page.

How To Display A Random Image From Directory In PHP?

Get all files from a directory and listing it using PHP

If the variable does not exist, then it will show “Variable does not exist” message on the web page. In our example it will show the variable value on our web page as the variable we already have defined.

Using the var_dump we can see the boolean result returned by the PHP isset() just like below:

var_dump(isset($var));

 

Leave a Reply

Your email address will not be published. Required fields are marked *