I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:
It's enough to check if the input is ''
or null
, because:
Request URL .../test.php?var=
results in $_GET['var'] = ''
Request URL .../test.php
results in $_GET['var'] = null
isset()
returns false
only when the variable exists and is not set to null
, so if you use it you'll get true
for empty strings (''
).
empty()
considers both null
and ''
empty, but it also considers '0'
empty, which is a problem in some use cases.
If you want to treat '0'
as empty, then use empty()
. Otherwise use the following check:
$var .'' !== ''
evaluates to false
only for the following inputs:
''
null
false
I use the following check to also filter out strings with only spaces and line breaks:
function hasContent($var){
return trim($var .'') !== '';
}