During your daily work with variables in PHP and JavaScript you often come across the query whether a variable is empty. It is worth knowing the native functions and their differences for checking. Annoyingly, there is no simple method to intuitively check whether a variable exists or not. What is meant by this is illustrated in the following matrix. However, small helper functions can be used to retrofit the desired function.
PHP
=== null | == null | is_null | isset | empty | if/else | ternary | count > 0 | == '' | === '' | @__x | |
$a | true | true | true | false | true | false | false | false | true | false | false |
null | true | true | true | false | true | false | false | false | true | false | false |
[] | false | true | false | true | true | false | false | false | false | false | false |
0 | false | true | false | true | true | false | false | true | true | false | true |
1 | false | false | false | true | false | true | true | true | false | false | true |
-1 | false | false | false | true | false | true | true | true | false | false | true |
'' | false | true | false | true | true | false | false | true | true | true | false |
' ' | false | false | false | true | false | true | true | true | false | false | false |
str | false | false | false | true | false | true | true | true | false | false | true |
[0,1] | false | false | false | true | false | true | true | true | false | false | true |
[0] | false | false | false | true | false | true | true | true | false | false | true |
new stdClass() | false | false | false | true | false | true | true | true | false | false | false |
Implementation of __x:
740550c6b3d2b9ae03e4d220eb08e6e3
The helper function __x is called with the error control operator @, which is usually not recommended, in order to check previously undefined variables.
JavaScript
=== null | == null | typeof input === 'undefined' | if/else | ternary | length > 0 | == '' | === '' | __x | |
$a | false | true | true | false | false | type error | false | false | false |
null | true | true | false | false | false | type error | false | false | false |
[] | false | false | false | true | true | false | true | false | false |
0 | false | false | false | false | false | false | true | false | true |
1 | false | false | false | true | true | false | false | false | true |
-1 | false | false | false | true | true | false | false | false | true |
'' | false | false | false | false | false | false | true | true | false |
' ' | false | false | false | true | true | true | false | false | false |
str | false | false | false | true | true | true | false | false | true |
[0,1] | false | false | false | true | true | true | false | false | true |
[0] | false | false | false | true | true | true | false | false | true |
new Object() | false | false | false | true | true | false | false | false | false |
Implementation of __x:
740550c6b3d2b9ae03e4d220eb08e6e3