In where shall I use isset() and !empty()
isset vs. !empty
FTA:
"isset() checks if a variable has a
value including (False, 0 or empty
string), but not NULL. Returns TRUE
if var exists; FALSE otherwise.On the other hand the empty() function
checks if the variable has an empty
value empty string, 0, NULL or
False. Returns FALSE if var has a
non-empty and non-zero value."
isset() and empty() - what to use
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:
- "" (an empty string)
- 0 (0 as an integer)
- 0.0 (0 as a float)
- "0" (0 as a string)
- NULL
- FALSE
- array() (an empty array)
- var $var; (a variable declared, but without a value in a class)
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
{...}
What's the difference between 'isset()' and '!empty()' in PHP?
ISSET checks the variable to see if it has been set. In other words, it checks to see if the variable is any value except NULL or not assigned a value. ISSET
returns TRUE
if the variable exists and has a value other than NULL. That means variables assigned a "", 0, "0", or FALSE are set, and therefore are TRUE
for ISSET
.
EMPTY checks to see if a variable is empty. Empty is interpreted as: "" (an empty string), 0 (integer), 0.0 (float)`, "0" (string), NULL, FALSE, array() (an empty array), and "$var;" (a variable declared, but without a value in a class.
Why check both isset() and !empty()
This is completely redundant. empty
is more or less shorthand for !isset($foo) || !$foo
, and !empty
is analogous to isset($foo) && $foo
. I.e. empty
does the reverse thing of isset
plus an additional check for the truthiness of a value.
Or in other words, empty
is the same as !$foo
, but doesn't throw warnings if the variable doesn't exist. That's the main point of this function: do a boolean comparison without worrying about the variable being set.
The manual puts it like this:
empty()
is the opposite of(boolean) var
, except that no warning is generated when the variable is not set.
You can simply use !empty($vars[1])
here.
Is empty() enough or use isset()?
Op codes generated from isset($var) && !empty($var)
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > EXT_STMT
1 ISSET_ISEMPTY_VAR 12800000 ~0 !0
2 > JMPZ_EX ~0 ~0, ->6
3 > ISSET_ISEMPTY_VAR 11800000 ~1 !0
4 BOOL_NOT ~2 ~1
5 BOOL ~0 ~2
6 > FREE ~0
4 7 > RETURN 1
and from !empty($var)
line # * op fetch ext return operands
---------------------------------------------------------------------------------
3 0 > EXT_STMT
1 ISSET_ISEMPTY_VAR 11800000 ~0 !0
2 BOOL_NOT ~1 ~0
3 FREE ~1
4 4 > RETURN 1
So yes it does repeat ISSET_ISEMPTY_VAR
but !$empty
. It depends on the value passed, but it it doesnt exist the top way is one opcode less BOOL_NOT
. but if it does exist, the bottom way is quicker.
Though its unlikely this is going to be a bottleneck in any application
How to avoid isset() and empty()
For those interested, I have expanded this topic into a small article, which provides the below information in a somewhat better structured form: The Definitive Guide To PHP's isset And empty
IMHO you should think about not just making the app "E_NOTICE compatible", but restructuring the whole thing. Having hundreds of points in your code that regularly try to use non-existent variables sounds like a rather badly structured program. Trying to access non-existent variables should never ever happen, other languages balk at this at compile time. The fact that PHP allows you to do it doesn't mean you should.
These warnings are there to help you, not to annoy you. If you get a warning "You're trying to work with something that doesn't exist!", your reaction should be "Oops, my bad, let me fix that ASAP." How else are you going to tell the difference between "variables that work just fine undefined" and honestly wrong code that may lead to serious errors? This is also the reason why you always, always, develop with error reporting turned to 11 and keep plugging away at your code until not a single NOTICE
is issued. Turning error reporting off is for production environments only, to avoid information leakage and provide a better user experience even in the face of buggy code.
To elaborate:
You will always need isset
or empty
somewhere in your code, the only way to reduce their occurrence is to initialize your variables properly. Depending on the situation there are different ways to do that:
Function arguments:
function foo ($bar, $baz = null) { ... }
There's no need to check whether $bar
or $baz
are set inside the function because you just set them, all you need to worry about is if their value evaluates to true
or false
(or whatever else).
Regular variables anywhere:
$foo = null;
$bar = $baz = 'default value';
Initialize your variables at the top of a block of code in which you're going to use them. This solves the !isset
problem, ensures that your variables always have a known default value, gives the reader an idea of what the following code will work on and thereby also serves as a sort of self-documentation.
Arrays:
$defaults = array('foo' => false, 'bar' => true, 'baz' => 'default value');
$values = array_merge($defaults, $incoming_array);
The same thing as above, you're initializing the array with default values and overwrite them with actual values.
In the remaining cases, let's say a template where you're outputting values that may or may not be set by a controller, you'll just have to check:
<table>
<?php if (!empty($foo) && is_array($foo)) : ?>
<?php foreach ($foo as $bar) : ?>
<tr>...</tr>
<?php endforeach; ?>
<?php else : ?>
<tr><td>No Foo!</td></tr>
<?php endif; ?>
</table>
If you find yourself regularly using array_key_exists
, you should evaluate what you're using it for. The only time it makes a difference is here:
$array = array('key' => null);
isset($array['key']); // false
array_key_exists('key', $array); // true
As stated above though, if you're properly initializing your variables, you don't need to check if the key exists or not, because you know it does. If you're getting the array from an external source, the value will most likely not be null
but ''
, 0
, '0'
, false
or something like it, i.e. a value you can evaluate with isset
or empty
, depending on your intent. If you regularly set an array key to null
and want it to mean anything but false
, i.e. if in the above example the differing results of isset
and array_key_exists
make a difference to your program logic, you should ask yourself why. The mere existence of a variable shouldn't be important, only its value should be of consequence. If the key is a true
/false
flag, then use true
or false
, not null
. The only exception to this would be 3rd party libraries that want null
to mean something, but since null
is so hard to detect in PHP I have yet to find any library that does this.
How can I use PHP's isset() in addition to empty()?
Is this what you mean?
$pagesize = (isset($_GET['pagesize']) && !empty($_GET['pagesize'])) ?
$_GET['pagesize'] :
20;
http://us.php.net/manual/en/language.operators.logical.php
EDIT:
To be complete, empty already checks if something is set, so you don't need to use isset() as well.
I would also caution against using this code if it is going directly into a query or something similar. Consider using intval, is_numeric and similar functions.
isset vs empty vs is_null
isset()
will check if the variable is set, ie
<?php
echo isset($var); // false
$var = 'hello';
empty()
will check if the variable is empty, ie
<?php
$emptyString = '';
echo empty($emptyString); // true
is_null()
will check for NULL
which is different from empty, because it's set to NULL
not an empty string. (NULL might be a confusing concept)
Since your title is a string, I think you want to be using empty()
if (!isset($_REQUEST[$name_input_name]) || empty($_REQUEST[$name_input_name])) {
$file->error = 'Please Enter a Title';
return false;
}
Related Topics
What's the Difference Between Isset() and Array_Key_Exists()
How to Push Both Value and Key into PHP Array
Using Jquery Ajax to Retrieve Data from MySQL
Html Element Array, Name="Something[]" or Name="Something"
Sum Values of Multidimensional Array by Key Without Loop
Where Does PHP'S Error Log Reside in Xampp
How to Check Uploaded File Type in PHP
Returning Json from PHP to JavaScript
Find a Matching or Closest Value in an Array
Are Arrays in PHP Copied as Value or as Reference to New Variables, and When Passed to Functions
How to Measure the Speed of Code Written in PHP
PHP Regex to Get Youtube Video Id
Why Would Json_Encode Return an Empty String
PHP String Replace Match Whole Word