Possible Duplicate:
Why check both isset() and !empty()
Could you help me to improve my coding style?:) In some tasks I need to check - is variable empty or contains something. To solve this task, I usually do the following.
Check - is this variable set or not? If it's set - I check - it's empty or not?
<?php
$var = '23';
if (isset($var)&&!empty($var)){
echo 'not empty';
}else{
echo 'is not set or empty';
}
?>
And I have a question - should I use isset() before empty() - is it necessary? TIA!
It depends what you are looking for, if you are just looking to see if it is empty just use
empty
as it checks whether it is set as well, if you want to know whether something is set or not useisset
.Empty
checks if the variable is set and if it is it checks it for null, "", 0, etcIsset
just checks if is it set, it could be anything not nullWith
empty
, the following things are considered empty:From http://php.net/manual/en/function.empty.php
As mentioned in the comments the lack of warning is also important with empty()
PHP Manual says
Regarding isset
PHP Manual says
Your code would be fine as:
For example:
Here are the outputs of
isset()
andempty()
for the 4 possibilities: undeclared, null, false and true.You'll notice that all the 'isset' results are opposite of the 'empty' results except for case
$b=false
. All the values (except null which isn't a value but a non-value) that evaluate to false will return true when tested for byisset
and false when tested by 'empty'.So use
isset()
when you're concerned about the existence of a variable. And useempty
when you're testing for true or false. If the actual type of emptiness matters, useis_null
and===0
,===false
,===''
.Empty returns true if the var is not set. But isset returns true even if the var is not empty.
This is a simple example. Hope it helps.
edit: added
isset
in the event a variable isn't defined like above, it would cause an error, checking to see if its first set at the least will help remove some headache down the road.In your particular case:
if ($var)
.You need to use
isset
if you don't know whether the variable exists or not. Since you declared it on the very first line though, you know it exists, hence you don't need to, nay, should not useisset
.The same goes for
empty
, only thatempty
also combines a check for the truthiness of the value.empty
is equivalent to!isset($var) || !$var
and!empty
is equivalent toisset($var) && $var
, orisset($var) && $var == true
.If you only want to test a variable that should exist for truthiness,
if ($var)
is perfectly adequate and to the point.You can just use empty() - as seen in the documentation, it will return false if the variable has no value.
An example on that same page:
You can use isset if you just want to know if it is not NULL. Otherwise it seems empty() is just fine to use alone.