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

How to Check if a Variable is Empty in ThinkPHP5

gitbox 2025-08-07

How to Determine if a Variable is Empty in ThinkPHP5

During development, it's common to need to check whether a variable is empty—especially when handling user input or data processing. ThinkPHP5, a popular PHP framework, supports both native PHP functions and its own built-in methods to make this process more efficient and flexible.

Using Native PHP Functions to Check for Empty Variables

PHP offers several built-in functions to check if a variable is set or empty. Here are the most frequently used methods.

isset() Function

The isset() function checks if a variable has been set and is not null. It’s useful for determining if a variable has been initialized.


if(isset($var)){
    // $var is set and not null
}else{
    // $var is either not set or null
}

empty() Function

The empty() function checks whether a variable is considered empty. Values like an empty string, 0, null, false, or an empty array are treated as empty.


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

Using ThinkPHP5 Framework Methods to Check for Empty Variables

In addition to native PHP methods, ThinkPHP5 offers several internal methods that simplify variable checks, especially in framework-based applications.

empty() Method

This method functions similarly to PHP's native empty(), and its usage is nearly identical.


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

is_null() Method

The is_null() method checks if a variable is exactly null, which is helpful when you specifically need to check for null values.


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

validate() Method

ThinkPHP5’s validate() method allows you to validate data against specific rules, making it very useful for form validation or user input checks.


use think\Validate;

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

$data = [
    'name'  => 'thinkphp',
    'email' => '[email protected]',
];

if(!$validate->check($data)){
    // Data did not pass validation
}else{
    // Data passed validation
}

Conclusion

Checking whether a variable is empty is an essential task in PHP and ThinkPHP5 development. This article outlined several effective ways to perform these checks, using both native PHP functions like isset() and empty(), and ThinkPHP5 methods such as is_null() and validate(). By choosing the appropriate method for your use case, you can write cleaner, more robust code.