Current Location: Home> Latest Articles> Common Methods to Check if a Variable is Empty in ThinkPHP5

Common Methods to Check if a Variable is Empty in ThinkPHP5

M66 2025-08-07

How to Check if a Variable is Empty in ThinkPHP5

In web development, checking if a variable is empty is a common requirement. Whether handling user input, receiving API parameters, or performing logic checks, verifying if a variable exists or holds a value is essential. ThinkPHP5, as a popular PHP framework, allows using native PHP functions as well as convenient framework methods. This article introduces several common ways to check if a variable is empty in ThinkPHP5.

Native PHP Methods to Check if a Variable is Empty

In ThinkPHP5, you can first use native PHP methods to determine if a variable is empty. These methods are simple, efficient, and suitable for quick checks.

Using the isset() Function

isset() checks if a variable is set and not null. It returns true if the variable exists and is not null; otherwise, false.


if(isset($var)){
    // $var exists and is not null
}else{
    // $var does not exist or is null
}

Using the empty() Function

empty() checks whether a variable is empty. It returns true if the variable is 0, "", null, false, or does not exist.


if(empty($var)){
    // $var is empty
}else{
    // $var is not empty
}

ThinkPHP5 Framework Methods to Check if a Variable is Empty

Besides PHP native functions, ThinkPHP5 also provides flexible methods to check if variables are empty. Here are some commonly used approaches.

Using empty() Method

In ThinkPHP5, you can still directly use the PHP native empty() function in the same way.


if(empty($var)){
    // $var is empty
}else{
    // $var is not empty
}

Using is_null() Method

is_null() checks if a variable is null and returns a boolean value. It is useful when you need to strictly check for null.


if(is_null($var)){
    // $var is null
}else{
    // $var is not null
}

Using validate() Method for Validation

ThinkPHP5's Validate class can validate formats and also check if variables are empty or meet specific rules.


use think\Validate;

$validate = new Validate([
    'name'  => 'require|max:25',
    'email' => 'email',
]);

$data = [
    'name'  => 'thinkphp',
    'email' => 'thinkphp@gmail.com',
];

if(!$validate->check($data)){
    // Variables do not meet rules
}else{
    // Variables meet rules
}

Summary

Whether using native PHP or ThinkPHP5 framework methods, checking if a variable is empty is an indispensable part of development. Beginners can start with isset() and empty(), while experienced developers may combine framework methods like is_null() and validate() for more complex logic. Choosing the appropriate method helps improve code quality and reduces runtime errors.