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 thatemptyis also combined with a check on the authenticity of the value.emptyis equivalent to!isset($var) || !$varand!emptyis equivalent toisset($var) && $varorisset($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
emptyas it will also check if it is set if you want to know if something is already set Set the setting or not usingisset.EmptyCheck whether the variable has been set. If it is set, check whether the variable is null, "", 0, etc.IssetJust 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:
$var = ""; if(empty($var)) // true because "" is considered empty {...} if(isset($var)) //true because var is set {...} if(empty($otherVar)) //true because $otherVar is null {...} if(isset($otherVar)) //false because $otherVar is not set {...}