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!
The isset() function is an inbuilt function in PHP that is used to determine if the variable is declared and its value is not equal to NULL. The empty() function is an inbuilt function in PHP that is used to check whether a variable is empty or not.
empty() function in PHP ? The isset() function is an inbuilt function in PHP which checks whether a variable is set and is not NULL. This function also checks if a declared variable, array or array key has null value, if it does, isset() returns false, it returns true in all other possible cases.
The equivalent of isset($var) for a function return value is func() === null . isset basically does a !== null comparison, without throwing an error if the tested variable does not exist.
The isset() function checks whether a variable is set, which means that it has to be declared and is not NULL. This function returns true if the variable exists and is not NULL, otherwise it returns false.
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 use isset
.
Empty
checks if the variable is set and if it is it checks it for null, "", 0, etc
Isset
just checks if is it set, it could be anything not null
With 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
empty() is the opposite of (boolean) var, except that no warning is generated when the variable is not set.
Regarding isset
PHP Manual says
isset() will return FALSE if testing a variable that has been set to NULL
Your code would be fine as:
<?php $var = '23'; if (!empty($var)){ echo 'not empty'; }else{ echo 'is not set or empty'; } ?>
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 {...}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With