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: