How to check variables in PHP?
By: Bahadır Mezgil
Tags: PHP, Web Development, Backend Development, Php Developers, Programming

PHP is a programming language created by Rasmus Lerdorf in 1994 whose main purpose was building websites. Right now we can say that it is a general-purpose server-side scripting language that is still heavily supported.

In PHP, we don’t always get expected values from variables. Because in real-life scenarios of software development, a developer may

forget to declare a variable or assign a value to the declared variable.

forget to pass the required parameter/parameters when calling a function.

use a result from an API request or database query which can have an undesired value.

access directly to global variables as Cookie or Session values that are not defined yet or have unexpected values.

Because of these kinds of scenarios in software development, as developers, we need to be more careful while coding around. We need to embrace the defensive programming approach which means that code in a way to prepare for handling unexpected circumstances and always be precautious.

In our case, that means when working with variables we should always expect variable values as unexpected or undesired and we should code by considering that. This should be one of the safest approaches to be followed for coding.

The PHP community already covered these kinds of scenarios with a lot of different solutions and in this article, we will cover these solutions with the following topics below:

The importance of checking variables How to check variables in PHP by using built-in functions Behaviors of these built-in functions Deciding to the right function

1. The importance of checking variables

There are a few examples of the side effects of using unchecked variables:

Scenario 1: Using an undeclared variable

echo $undeclaredVariable;

Output:

PHP Notice: Undefined variable: undeclaredVariable

Scenario 2: Using an unwanted variable value

$emptyUserLastname = "";

echo "Hi Mr. " . $emptyUserLastname;

Output:

Hi Mr.

Scenario 3: Using pretentious service call response

function getUserUnsuccessful() {

return array();

}

$user = getUserUnsuccessful();

echo "Welcome Mr. " . $user["LASTNAME"];

Output:

PHP Notice: Undefined index: LASTNAME

Scenario 4: Using Unchecked GLOBAL variable

echo $_COOKIE["USER_ID"];

Output:

PHP Notice: Undefined index: USER_ID

In these scenarios, you can see some PHP notices and some unexpected behaviors. Of course, in these kinds of situations, your code won’t crash or terminate but later because of this unchecked variable usage, you can face unexpected behavior of your algorithm which has also another name as bugs.

2. How to check variables in PHP by using built-in functions

Luckily PHP has a lot of built-in functions to check variables. But we can’t use them without knowing their exact behavior. Because it can lead us to face unexpected behavior of our algorithm. In order to avoid it first, we need to know which functions we can use and what their exact behaviors are.

What I like most about PHP is that you don’t need any third-party library to solve these kinds of situations, because the PHP community already covered a lot of different subjects with built-in functions. So you don’t need to reinvent the wheel.

The second favorite part about PHP is almost every built-in function is readable which means you can understand their purpose and behavior by just reading the function name.

Warning: the usage of any function in PHP can be problematic in terms of how to pass parameters or knowing the return value. This is one of the most complained things about PHP. The creator of PHP Rasmus Lerdorf even mentioned that they did not have any good examples in those old days. They only had C implementations as examples. They chose to stick with that in order to achieve things in a short period of time.

In PHP, there are two commonly used functions for variable check as isset() and empty(). Now let’s see these built-in functions to check variables and their exact behaviors.

3. Behaviors of these built-in functions

isset()

As it can be understood from the function name, it checks whether the given parameter is set to any value or not. So it accepts a variable as a parameter and checks the given parameter as it

is declared

is assigned

have any values except null.

If the variable has all these conditions, isset() function will return TRUE. Otherwise, it will return FALSE.

Here are some examples to use the isset() function:

var_dump(isset($undeclaredVariable)); // prints bool(false)



$declaredVariable;

var_dump(isset($declaredVariable)); // prints bool(false)



$declaredAndAssignedVariable = NULL;

var_dump(isset($declaredAndAssignedVariable)); // prints bool(false)



$declaredAndAssignedVariableOtherThanNull = 1;

var_dump(isset($declaredAndAssignedVariableOtherThanNull)); // prints bool(true)



$boolean = FALSE;

var_dump(isset($boolean)); // prints bool(true)



$boolean = TRUE;

var_dump(isset($boolean)); // prints bool(true)



$string = "";

var_dump(isset($string)); // prints bool(true)



$string = "0";

var_dump(isset($string)); // prints bool(true)



$string = "A";

var_dump(isset($string)); // prints bool(true)



$integer = 0;

var_dump(isset($integer)); // prints bool(true)



$integer = 1;

var_dump(isset($integer)); // prints bool(true)



$float = 0.0;

var_dump(isset($float)); // prints bool(true)



$float = 0.1;

var_dump(isset($float)); // prints bool(true)



$array = array();

var_dump(isset($array)); // prints bool(true)



$array = array("A");

var_dump(isset($array)); // prints bool(true)

PHP accepts its value as NULL for undeclared and unassigned variables. As you can see that other than undeclared, unassigned and NULL values, isset() function returns TRUE. The case isset() function is very useful when we want to ensure whether the variable is declared, assigned or not NULL.

empty()

We may misunderstand the function’s purpose from the function name. It looks like it makes the given parameter empty but actually it only checks whether the given parameter is empty or not. I can hear the objections like isEmpty() could be a better name for this function.

But again it is the old times’ problem and because of the heritage (not the sacred one, the one to support backward compatibility of new PHP versions and to encourage old version users to update their PHP versions), it stayed in that way.

In short, the empty() function accepts one parameter to check the given variable is empty or not. When we look at its behavior it behaves like the isset() function plus checking variable value emptiness which means if the given parameter equals:

NULL

integer 0, double 0.00, float 0.0

an empty string(“)

boolean FALSE

empty array

Also, this function has an edge case which also assumes a string with “0”, “0.0”, “0.00..” characters as empty as well.

In these cases above, it returns TRUE because empty function accepts these values as empty.

But why?

Because empty() function variable emptiness means that checking the variable value in terms of boolean equality. So PHP decides whether the given variable value boolean equality is true or false.

We can see the boolean equality of values with boolval() function which returns a boolean value of a given parameter from https://www.php.net/manual/en/function.boolval.php. So in PHP:

NULL

integer 0

double 0.00

float 0.0…

an empty string(“)

boolean FALSE

empty array

Values boolean equalities are FALSE. Based on that if we sum up the empty() function:

empty() = isset() + boolval()

We can easily understand the empty() function behavior by this formula. We can say that empty() function is wider variable check function than isset() function. So we don’t need to use isset() and empty() functions together in the same case. It is all about deciding empty value of the variable is bother us or not. Eventually, we should use at least one of them handling variables in PHP.

Here some examples to use empty function()

var_dump(empty($undeclaredVariable)); // prints bool(true)



$declaredVariable;

var_dump(empty($declaredVariable)); // prints bool(true)



$declaredAndAssignedVariable = NULL;

var_dump(empty($declaredAndAssignedVariable)); // prints bool(true)



$declaredAndAssignedVariableOtherThanNull = 1;

var_dump(empty($declaredAndAssignedVariableOtherThanNull)); // prints bool(false)



$boolean = FALSE;

var_dump(empty($boolean)); // prints bool(true)



$boolean = TRUE;

var_dump(empty($boolean)); // prints bool(false)



$string = "";

var_dump(empty($string)); // prints bool(true)



// Edge case, empty() accepts "0", "0.0", "0.00", "0.000..." strings as empty strings

$string = "0";

var_dump(empty($string)); // prints bool(true)



$string = "A";

var_dump(empty($string)); // prints bool(false)



$integer = 0;

var_dump(empty($integer)); // prints bool(true)



$integer = 1;

var_dump(empty($integer)); // prints bool(false)



$float = 0.0;

var_dump(empty($float)); // prints bool(true)



$float = 0.1;

var_dump(empty($float)); // prints bool(false)



$array = array();

var_dump(empty($array)); // prints bool(true)



$array = array("A");

var_dump(empty($array)); // prints bool(false)

So now we know that we can use isset() and empty() functions to check variables. As we implement them to our example scenarios as:

Scenario 1: Using an undeclared variable

if(isset($undeclaredVariable)) {

echo $undeclaredVariable;

} else {

echo "We found an undeclared variable.";

}

Output:

We found an undeclared variable.

Scenario 2: Using an unwanted variable value

$emptyUserLastname = ""; if(!empty($emptyUserLastname)) {

echo "Hi Mr. " . $emptyUserLastname;

} else {

echo "Hi Mr. Anonymous";

}

Output:

Hi Mr. Anonymous

Scenario 3: Using pretentious service call response

function getUserUnsuccessful() {

return array();

} $user = getUserUnsuccessful(); if(!empty($user["LASTNAME"])) {

echo "Welcome Mr. " . $user["LASTNAME"] . "

";

} else {

echo "Hi Mr. Anonymous";

}

Output:

Hi Mr. Anonymous

Scenario 4: Using Unchecked GLOBAL variable

if(isset($_COOKIE["USER_ID"])){

echo $_COOKIE["USER_ID"];

} else {

echo "User Id is not available.";

}

Output:

User Id is not available.

For all updated code scenarios, we get rid of PHP Notice messages. For scenario 1 and 4, we warn our users, for scenario 2 and 3, we dodge the unwanted algorithm behavior.

The case that empty() function is useful to check whether the given variable is declared, assigned and doesn’t have an empty value. But we need to be careful about edge cases as string “0”, “0.0”, “0.00”, integer 0, double 0.00, float 0.0 so on. Because in these edge cases, our algorithm may accept these values as not empty. So our algorithm may work in an unexpected way if we regard this kind of situation.

4. Deciding to the right function

The trick to decide to use isset() or empty() function is:

If the case about the variable is we should consider it is declared, assigned or not null, use isset()

If the case is more than that also we care about is whether variable empty or not, use empty(). But always consider the edge cases of empty() function.

Don’t use isset() and empty() functions together to check the same case. It will be unnecessary code repetition.

Only isset() and empty() functions are not enough to apply a defensive approach completely. We need to add extra checks with additional PHP built-in functions as:

is_null

is_bool

is_numeric

is_float

is_int

is_string

is_array

Is_object

This article doesn’t cover these extra PHP built-in functions but you can understand their behaviors easily by just reading them. Also, you can check their exact behaviors from https://www.php.net/manual/ by typing the function name on the search box. They can add an extra precaution to your algorithm if you use them alongside isset() or empty() function.

Thanks for reading this article. I hope it helps you with how to deal with variables in PHP. You should always use the defensive approach in programming. It is a very beneficial habit to have which will also help you in the future to become a better programmer.