🧑‍🎓

#57 isset() vs empty() What's the differences?

2024/09/19に公開

isset() vs empty() What's the differences?

While start learning PHP, there are always some points which is confusing. Today I would like to make a simple note to descript the differences between isset(), empty(), if()

What is isset()?

Determine if a variable is declared and is different than null

Simply saying it checks whether a variable is set and NOT equal to NULL

What is empty()?

Determine whether a variable is empty

All the variables including , 0,false and NULL are empty.

In the offical document, we are able to find out empty() run the concise above.

!isset($var) || $var == false

isset() vs empty()

empty() using isset() to determine whether the value is empty.

It looks similar but working for different purpose, so do not get it wrong otherwise it may cause you a big trouble.

Forturnately, PHP official document provide type comparison tables which clearly showing the differences.
https://www.php.net/manual/en/types.comparisons.php

Frequent issues

While receiving API response or checking SQL query data, we oftenly use empty to check whether the variable is null or empty. It is still easy to understand while checking empty string. But how about 0?

0 is used in different situations and defined as a non-empty variable. However, if(!empty($x))is oftenly seen to be used for validation and clearly it cause bug because 0 is define as empty variable in PHP.

It is simple to fix, like replace empty with isset. But we should learn the definition before using any 'language construct'.

Conclusion

Does not like Java, PHP is not a statically-typed language, you might make a mistake without notice. Therefore read the document carefully, it is really helpful.

Reference

https://www.php.net/manual/en/function.isset.php
https://www.php.net/manual/en/function.empty.php
https://www.php.net/manual/en/types.comparisons.php

Discussion