In where shall I use isset() and !empty() [duplicate]
Asked Answered
F

20

130

I read somewhere that the isset() function treats an empty string as TRUE, therefore isset() is not an effective way to validate text inputs and text boxes from a HTML form.

So you can use empty() to check that a user typed something.

  1. Is it true that the isset() function treats an empty string as TRUE?

  2. Then in which situations should I use isset()? Should I always use !empty() to check if there is something?

For example instead of

if(isset($_GET['gender']))...

Using this

if(!empty($_GET['gender']))...
Frenum answered 2/8, 2009 at 19:0 Comment(0)
G
157

isset() checks if a variable has a value, including False, 0 or empty string, but not including NULL. Returns TRUE if var exists and is not NULL; FALSE otherwise.

empty() does a reverse to what isset does (i.e. !isset()) and an additional check, as to whether a value is "empty" which includes an empty string, 0, NULL, false, or empty array or object False. Returns FALSE if var is set and has a non-empty and non-zero value. TRUE otherwise

Granoff answered 2/8, 2009 at 19:4 Comment(3)
FTA: From the ArticleOfeliaofella
empty() also returns true for an empty array.Dihedral
Even tho empty() returns TRUE for 0, it's not a good idea to use this operator for math in case "0" is accidentally a string. This can be dangerous. Instead, use basic >, < and == operators and convert variables using intval() or floatval().Westfalen
C
41

In the most general way :

  • isset tests if a variable (or an element of an array, or a property of an object) exists (and is not null)
  • empty tests if a variable is either not set or contains an empty-like value.

To answer question 1 :

$str = '';
var_dump(isset($str));

gives

boolean true

Because the variable $str exists.

And question 2 :

You should use isset to determine whether a variable exists; for instance, if you are getting some data as an array, you might need to check if a key is set in that array (and its value is not null).
Think about $_GET / $_POST, for instance.

If you want to know whether a variable exists and not "empty", that is the job of empty.

Cammiecammy answered 2/8, 2009 at 19:6 Comment(0)
R
12

isset is intended to be used only for variables and not just values, so isset("foobar") will raise an error. As of PHP 5.5, empty supports both variables and expressions.

So your first question should rather be if isset returns true for a variable that holds an empty string. And the answer is:

$var = "";
var_dump(isset($var));

The type comparison tables in PHP’s manual is quite handy for such questions.

isset basically checks if a variable has any value other than null since non-existing variables have always the value null. empty is kind of the counter part to isset but does also treat the integer value 0 and the string value "0" as empty. (Again, take a look at the type comparison tables.)

Romany answered 2/8, 2009 at 19:12 Comment(1)
Note that empty() also "supports expressions, rather than only variables" as of PHP 5.5.0.Aruwimi
L
12

Neither is a good way to check for valid input.

  • isset() is not sufficient because – as has been noted already – it considers an empty string to be a valid value.
  • ! empty() is not sufficient either because it rejects '0', which could be a valid value.

Using isset() combined with an equality check against an empty string is the bare minimum that you need to verify that an incoming parameter has a value without creating false negatives:

if( isset($_GET['gender']) and ($_GET['gender'] !== '') )
{
  ...
}

But by "bare minimum", I mean exactly that. All the above code does is determine whether there is some value for $_GET['gender']. It does not determine whether the value for $_GET['gender'] is valid (e.g., one of ("Male", "Female", "FileNotFound")).

For that, see Josh Davis's answer.

Lemuellemuela answered 22/4, 2012 at 4:24 Comment(1)
Because you are using a loose comparison, your suggested snippet will give false positives when handling a zero-ish/falsey non-string value. 3v4l.org/aIWqAUnarm
C
10

If you have a $_POST['param'] and assume it's string type then

isset($_POST['param']) && $_POST['param'] != ''

is identical to

!empty($_POST['param'])
Combust answered 26/1, 2013 at 17:18 Comment(0)
A
6

isset() vs empty() vs is_null()

enter image description here

Adhesive answered 28/11, 2019 at 20:33 Comment(0)
B
5

When and how to use:

  1. isset()

True for 0, 1, empty string, a string containing a value, true, false

False undefined variable for null

e.g

$status = 0
if (isset($status)) // True
$status = null 
if (isset($status)) // False
  1. Empty

False for 1, a string containing a value, true

True for undefined value, null, empty string, 0, false e.g

$status = 0
if(empty($status)) // true
$status = 1
if(empty($status)) // False
Blakemore answered 14/5, 2017 at 7:18 Comment(0)
R
4

isset() is not an effective way to validate text inputs and text boxes from a HTML form

You can rewrite that as "isset() is not a way to validate input." To validate input, use PHP's filter extension. filter_has_var() will tell you whether the variable exists while filter_input() will actually filter and/or sanitize the input.

Note that you don't have to use filter_has_var() prior to filter_input() and if you ask for a variable that is not set, filter_input() will simply return null.

Ramses answered 2/8, 2009 at 20:59 Comment(0)
W
2
isset($variable) === (@$variable !== null)
empty($variable) === (@$variable == false)
Warms answered 2/8, 2009 at 19:6 Comment(0)
K
2

isset is used to determine if an instance of something exists that is, if a variable has been instantiated... it is not concerned with the value of the parameter...

Pascal MARTIN... +1 ...

empty() does not generate a warning if the variable does not exist... therefore, isset() is preferred when testing for the existence of a variable when you intend to modify it...

Kowalczyk answered 13/6, 2014 at 12:4 Comment(0)
S
2

isset() is used to check if the variable is set with the value or not and Empty() is used to check if a given variable is empty or not.

isset() returns true when the variable is not null whereas Empty() returns true if the variable is an empty string.

Sheridan answered 17/5, 2018 at 15:23 Comment(0)
I
0

I came here looking for a quick way to check if a variable has any content in it. None of the answers here provided a full solution, so here it is:


It's enough to check if the input is '' or null, because:

Request URL .../test.php?var= results in $_GET['var'] = ''

Request URL .../test.php results in $_GET['var'] = null


isset() returns false only when the variable exists and is not set to null, so if you use it you'll get true for empty strings ('').

empty() considers both null and '' empty, but it also considers '0' empty, which is a problem in some use cases.

If you want to treat '0' as empty, then use empty(). Otherwise use the following check:

$var .'' !== '' evaluates to false only for the following inputs:

  • ''
  • null
  • false

I use the following check to also filter out strings with only spaces and line breaks:

function hasContent($var){
    return trim($var .'') !== '';
}
Impellent answered 25/2, 2020 at 20:48 Comment(0)
M
-1

Using empty is enough:

if(!empty($variable)){
    // Do stuff
}

Additionally, if you want an integer value it might also be worth checking that intval($variable) !== FALSE.

Mors answered 2/8, 2009 at 19:5 Comment(2)
Also, intval() never returns FALSE.Ramses
its NOT enough since '0' is a valid string but not for empty... isset/filter_has_var must be used to check if var exist.Fairlie
T
-1

I use the following to avoid notices, this checks if the var it's declarated on GET or POST and with the @ prefix you can safely check if is not empty and avoid the notice if the var is not set:

if( isset($_GET['var']) && @$_GET['var']!='' ){
    //Is not empty, do something
}
Tweezers answered 7/8, 2017 at 18:8 Comment(2)
The "stfu operator" (@) should not be encouraged and it is not necessary for your snippet. This is not a good answer. You are doing a loose comparison. You may as well use !empty().Unarm
Ooo man... This is great for the bad coding example. @ will give you in the trouble with debugging, page impact is slower and you still can have error_log over 1GB in one moment. Just be smart and use !empty(), !is_null() or something like that.Hyperesthesia
V
-1
    $var = '';
// Evaluates to true because $var is empty
if ( empty($var) ) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if ( isset($var) ) {
 echo '$var is set even though it is empty';
    }

Source: Php.net

Viridian answered 10/7, 2018 at 11:40 Comment(0)
E
-1

isset() tests if a variable is set and not null:

http://us.php.net/manual/en/function.isset.php

empty() can return true when the variable is set to certain values:

http://us.php.net/manual/en/function.empty.php

<?php

$the_var = 0;

if (isset($the_var)) {
  echo "set";
} else {
  echo "not set";
}

echo "\n";

if (empty($the_var)) {
  echo "empty";
} else {
  echo "not empty";
}
?>
Elsaelsbeth answered 26/3, 2019 at 12:2 Comment(0)
F
-1

!empty will do the trick. if you need only to check data exists or not then use isset other empty can handle other validations

<?php
$array = [ "name_new" => "print me"];

if (!empty($array['name'])){
   echo $array['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array2 = [ "name" => NULL];

if (!empty($array2['name'])){
   echo $array2['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array3 = [ "name" => ""];

if (!empty($array3['name'])){
   echo $array3['name'];
}

//output : {nothing}  

////////////////////////////////////////////////////////////////////

$array4 = [1,2];

if (!empty($array4['name'])){
   echo $array4['name'];
}

//output : {nothing}

////////////////////////////////////////////////////////////////////

$array5 = [];

if (!empty($array5['name'])){
   echo $array5['name'];
}

//output : {nothing}

?>

Fassold answered 3/6, 2020 at 9:34 Comment(0)
A
-1

Please consider behavior may change on different PHP versions

From documentation

isset() Returns TRUE if var exists and has any value other than NULL. FALSE otherwise https://www.php.net/manual/en/function.isset.php

empty() does not exist or if its value equals FALSE https://www.php.net/manual/en/function.empty.php

(empty($x) == (!isset($x) || !$x)) // returns true;

(!empty($x) == (isset($x) && $x)) // returns true;

Ansela answered 13/11, 2020 at 2:56 Comment(0)
C
-1

When in doubt, use this one to check your Value and to clear your head on the difference between isset and empty.

if(empty($yourVal)) {
  echo "YES empty - $yourVal"; // no result
}
if(!empty($yourVal)) {
  echo "<P>NOT !empty- $yourVal"; // result
}
if(isset($yourVal)) {
  echo "<P>YES isset - $yourVal";  // found yourVal, but result can still be none - yourVal is set without value
}
if(!isset($yourVal)) {
  echo "<P>NO !isset - $yourVal"; // $yourVal is not set, therefore no result
}
Curio answered 16/10, 2021 at 0:5 Comment(0)
R
-1

The following use for the two php constructs will help you choose the best fit in your case.

Short story

empty checks if the variable is set/defined and if it is it checks it for null,false, "", 0.

isset just checks if is it set, it could be anything not null

Long story

The isset verifies if a variable has been defined and holds any value, the value could be anything not null.

On the other hand, empty not only checks if the variable is set but also examines if it contains a value that is considered "empty," such as null, an empty string '',false, or 0.

Rochellrochella answered 14/8, 2023 at 9:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.