Can you help me improve my coding style? :) In some tasks I need to check - if a variable is empty or contains something. To solve this task, I usually do the following.
Check - Is this variable already set? If it is set - I check - is it empty?
<?php $var = '23'; if (isset($var)&&!empty($var)){ echo 'not empty'; }else{ echo 'is not set or empty'; } ?>
I have a question - should I use isset() before empty() - is it necessary? TIA!
In your specific case:
if ($var)
.If you don't know if the variable exists , you need to use
isset
. Since you declared it on the first line, you know it exists, so you don't need to, and no, shouldn't useisset
.The same is true for
empty
, except thatempty
is also combined with a check on the authenticity of the value.empty
is equivalent to!isset($var) || !$var
and!empty
is equivalent toisset($var) && $var
orisset($var) && $var == correct
.If you just want to test the authenticity of a variable that should exist ,
if ($var)
is completely sufficient. .It depends on what you are looking for, if you just want to see if it is empty use
empty
as it will also check if it is set if you want to know if something is already set Set the setting or not usingisset
.Empty
Check whether the variable has been set. If it is set, check whether the variable is null, "", 0, etc.Isset
Just checks if it is set, it can be anything that is not emptyFor
empty
, the following is considered empty:From http://php.net/manual/en/function.empty.php
As mentioned in the comments, the lack of warnings is also important for empty()
PHP Manualsays
About the question
PHP Manualsays
Your code will do:
For example: